我有一个非常简单的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);
}
Run Code Online (Sandbox Code Playgroud)
编译错误:
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;`
Run Code Online (Sandbox Code Playgroud)
如果我明确导入特征,它可以工作:
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);
}
Run Code Online (Sandbox Code Playgroud)
我为什么需要use rustc_serialize::base64::ToBase64;?
Chr*_*gan 22
这就是它的方式.在Rust中,特征必须在范围内,以便您能够调用其方法.
至于为什么,碰撞的可能性就是原因.在所有格式的性状std::fmt(Display,Debug,LowerHex,&C)有相同的方法签名fmt.例如; 怎么object.fmt(&mut writer, &mut formatter)办?Rust的答案是"你必须通过在方法范围内具有特征来明确指出."
另请注意错误消息如何表示" 当前作用域中没有为类型`T`找到名为`m`的方法".
请注意,您不具备导入它,如果你想使用特征方法的功能,而不是一个方法:
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3686 次 |
| 最近记录: |