rust - 为什么需要导入特征以使用它为类型定义的方法?

标签 rust

我有一个非常简单的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中的所有格式特征(DisplayDebugLowerHex和&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/

相关文章:

methods - 无论如何, “context”和 “with_context”有什么区别?

rust - 如何从方法返回特征的实例?

rust - 如何在match语句中使用const范围? [复制]

rust - 如何获取枚举的整数值?

rust - 在 Rust 中对字符串进行分区

rust - 如何防止ruSTLib在aarch64上引用软 float 函数?

rust - 是否有可能有一个结构引用了一个生命周期可以更短的子结构?

rust - 从Vec移除一系列元素

rust - for <'r, ' s> fn( &'r MyType<' s>) -> bool 在 `impl std::fmt::Debug` 定义中的什么位置?

rust - 调用cargo-binutils命令时,是否可以使用xbuild代替build?