gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:20:24 27 4
gpt4 key购买 nike

我有一个非常简单的无法编译的 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);
}

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

最佳答案

事情就是这样。在 Rust 中,特征必须在范围内,您才能调用它的方法。

至于为什么,碰撞的可能性就是原因。 std::fmt 中的所有格式特征(DisplayDebugLowerHex 等)具有相同的格式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/52618825/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com