为什么我需要导入特征才能使用它为类型定义的方法? [英] Why do I need to import a trait to use the methods it defines for a type?

查看:26
本文介绍了为什么我需要导入特征才能使用它为类型定义的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的 Rust 代码示例,但无法编译:

I have a very simple example of Rust code which fails to compile:

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;`

如果我显式导入特征,它会起作用:

It works if I import the trait explicitly:

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);
}

为什么我需要使用 rustc_serialize::base64::ToBase64;?

推荐答案

就是这样.在 Rust 中,特征必须在范围内才能调用其方法.

That’s simply the way it is. In Rust a trait must be in scope for you to be able to call its methods.

至于why,碰撞的可能性是原因.std::fmt (Display, Debug, LowerHex, &c.) 中的所有格式特征都有fmt 的相同方法签名.例如;例如,object.fmt(&mut writer, &mut formatter) 会做什么?Rust 的回答是你必须通过在方法所在的范围内使用 trait 来明确指示."

As for why, the possibility of collisions is the reason why. All the formatting traits in std::fmt (Display, Debug, LowerHex, &c.) have the same method signature for fmt. For example; what would object.fmt(&mut writer, &mut formatter) do, for example? Rust’s answer is "you must explicitly indicate by having the trait in scope where the method is."

还要注意错误消息如何说明在当前作用域中没有为类型‘T’找到名为‘m’的方法".

Note also how the error message says that "no method named `m` found for type `T` in the current scope".

请注意,如果要将 trait 方法用作函数而不是方法,则不必导入它:

Note that you don't have to import it if you want to use the trait method as a function instead of a method:

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);
}

这篇关于为什么我需要导入特征才能使用它为类型定义的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆