[英]Why do I need to import a trait to use the methods it defines for a type?
I have a very simple example of Rust code which fails to compile:我有一个非常简单的 Rust 代码示例,它无法编译:
extern crate rustc_serialize;
use rustc_serialize::base64;
fn main() {
let auth = format!("{}:{}", "user", "password");
let auth_b64 = auth.as_bytes().to_base64(base64::MIME);
println!("Authorization string: {}", auth_b64);
}
The compiler error:编译器错误:
error[E0599]: no method named `to_base64` found for type `&[u8]` in the current scope
--> src/main.rs:6:36
|
6 | let auth_b64 = auth.as_bytes().to_base64(base64::MIME);
| ^^^^^^^^^
|
= help: items from traits can only be used if the trait is in scope
= note: the following trait is implemented but not in scope, perhaps add a `use` for it:
candidate #1: `use rustc_serialize::base64::ToBase64;`
It works if I import the trait explicitly:如果我明确导入特征,它会起作用:
extern crate rustc_serialize;
use rustc_serialize::base64::{self, ToBase64};
fn main() {
let auth = format!("{}:{}", "user", "password");
let auth_b64 = auth.as_bytes().to_base64(base64::MIME);
println!("Authorization string: {}", auth_b64);
}
Why do I need to use rustc_serialize::base64::ToBase64;
为什么我需要use rustc_serialize::base64::ToBase64;
? ?
That's simply the way it is.就是这样。 In Rust a trait must be in scope for you to be able to call its methods.在 Rust 中,特征必须在范围内才能调用其方法。
As for why , the possibility of collisions is the reason why.至于为什么,碰撞的可能性是原因。 All the formatting traits in std::fmt
( Display
, Debug
, LowerHex
, &c.) have the same method signature for fmt
. std::fmt
所有格式特征( Display
、 Debug
、 LowerHex
等)都具有相同的fmt
方法签名。 For example;例如; what would object.fmt(&mut writer, &mut formatter)
do, for example?例如, object.fmt(&mut writer, &mut formatter)
做什么? Rust's answer is “you must explicitly indicate by having the trait in scope where the method is.” Rust 的回答是“您必须通过在方法所在的范围内使用 trait 来明确指示。”
Note also how the error message says that “no method named `m` found for type `T` in the current scope ”.另请注意错误消息如何说明“在当前范围内找不到类型‘T’的名为‘m’的方法”。
Note that you don't have to import it if you want to use the trait method as a function instead of a method:请注意,您不必导入它,如果你想使用的特征方法的功能,而不是一个方法:
extern crate rustc_serialize;
use rustc_serialize::base64;
fn main() {
let auth = format!("{}:{}", "user", "password");
let auth_b64 = rustc_serialize::base64::ToBase64::to_base64(auth.as_bytes(), base64::MIME);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
println!("Authorization string: {}", auth_b64);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.