gpt4 book ai didi

rust - 如何消除Rust的特征?

转载 作者:行者123 更新时间:2023-12-03 11:48:58 27 4
gpt4 key购买 nike

我想在两种不同类型的对象上使用write_fmt方法:

use std::fmt::Write;
use std::io::Write;

fn main() {
let mut a = String::new();
let mut b = std::fs::File::create("test").unwrap();

a.write_fmt(format_args!("hello"));
b.write_fmt(format_args!("hello"));
}

使用 Write时出现错误,因为它们的名称相同:

error[E0252]: a trait named `Write` has already been imported in this module
--> src/main.rs:8:5
|
7 | use std::fmt::Write;
| --------------- previous import of `Write` here
8 | use std::io::Write;
| ^^^^^^^^^^^^^^ `Write` already imported
a.write_fmt(format_args!("hello"));
b.write_fmt(format_args!("hello"));

或我收到一条错误消息,指出该特征不可用:

error[E0599]: no method named `write_fmt` found for type `std::fs::File` in the current scope
--> src/main.rs:76:4
|
76 | b.write_fmt(format_args!("hello"));
| ^^^^^^^^^
|
= help: items from traits can only be used if the trait is in scope; the following trait is implemented but not in scope, perhaps add a `use` for it:
= help: candidate #1: `use std::io::Write;`

最佳答案

您可以直接调用trait方法:

fn main() {
let mut a = String::new();
let mut b = std::fs::File::create("test").unwrap();

std::fmt::Write::write_fmt(&mut a, format_args!("hello"));
std::io::Write::write_fmt(&mut b, format_args!("hello"));
}

您还可以选择仅在较小的范围内导入特征:
fn main() {
let mut a = String::new();
let mut b = std::fs::File::create("test").unwrap();

{
use std::fmt::Write;
a.write_fmt(format_args!("hello"));
}

{
use std::io::Write;
b.write_fmt(format_args!("hello"));
}
}

请注意,如果您选择使用较小的范围,则还可以直接使用 write!宏:
fn main() {
let mut a = String::new();
let mut b = std::fs::File::create("test").unwrap();

{
use std::fmt::Write;
write!(a, "hello");
}

{
use std::io::Write;
write!(b, "hello");
}
}

无论哪种情况,都应处理 Result返回值。

也可以看看:
  • How to call a method when a trait and struct use the same name?
  • 关于rust - 如何消除Rust的特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61488992/

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