我有一个非常简单的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);
}
编译错误:
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;`
如果我明确导入特征,它会起作用:
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);
}
为什么我需要use rustc_serialize::base64::ToBase64;
?
答案 0 :(得分:18)
这就是它的方式。在Rust中,特征必须在范围内,以便您能够调用其方法。
至于为什么,碰撞的可能性就是原因所在。 std::fmt
(Display
,Debug
,LowerHex
和&。c。)中的所有格式特征与fmt
具有相同的方法签名。例如;例如,object.fmt(&mut writer, &mut formatter)
会做什么? Rust的答案是“你必须通过在方法范围内具有特征来明确指出。”
另请注意错误消息如何表示“当前范围”中没有找到名为`m`的类型`T` 。
请注意,如果您想将trait方法用作函数而不是方法,则不要 导入它:
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);
}