我有一个非常简单的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;
?
最佳答案
就是这样。在Rust中,特征必须在范围内,以便您能够调用其方法。
至于为什么,发生碰撞的可能性就是原因。 std::fmt
中的所有格式特征(Display
,Debug
,LowerHex
和&c。)都具有fmt
的相同方法签名。例如;例如,object.fmt(&mut writer, &mut formatter)
会做什么? Rust的回答是“您必须通过在方法所在的范围内具有特征来明确指出。”
还要注意错误消息是如何说的:“在当前作用域中没有找到类型为T的名为m的方法”。
请注意,如果您想将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);
}
关于rust - 为什么需要导入特征以使用它为类型定义的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62016247/