Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

How do I disambiguate traits in Rust?

I want to use the write_fmt method on two different types of object:

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

I get an error when using Write because they are both named the same:

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

Or I get an error saying the trait is not available:

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;`
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can call the trait method directly:

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

You can also choose to only import the trait in a smaller scope:

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

Note that if you choose to use a smaller scope, you can also use the write! macro directly:

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

In either case, you should handle the Result return value.

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...