【发布时间】:2014-10-06 02:01:09
【问题描述】:
我有一个非常简单的无法编译的 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 1.33 开始,如果您不需要使用其名称来引用 trait,您可以像
use Trait as _;一样导入它。这有助于解决名称冲突。
标签: rust