How do I disambiguate traits in Rust?

前端 未结 2 1034
我寻月下人不归
我寻月下人不归 2020-11-28 15:18

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 = Strin         


        
2条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 15:47

    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:

    • How to call a method when a trait and struct use the same name?

提交回复
热议问题