V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
liuser666
V2EX  ›  Rust

rust 为什么用 Trait 需要手动引入 trait?

  •  1
     
  •   liuser666 · Feb 4, 2023 · 3048 views
    This topic created in 1188 days ago, the information mentioned may be changed or developed.

    use std::net::TcpListener; use std::io::{Read,Write};

    fn main(){ let listener = TcpListener::bind("127.0.0.1:4000").unwrap(); println!("Running on port 4000....");

    // let result = listener.accept().unwrap();
    for stream in listener.incoming(){
        let mut stream = stream.unwrap();
        println!("connection established");
        let mut buffer = [0; 1024];
        
        stream.read(&mut buffer).unwrap();
        
    
    
    }
    

    } 为什么非要 use std::io::{Read,Write};显式地引入 Trait 呢? impl trait Read 的代码不是在 TcpListener 里已经有了吗?

    4 replies    2023-06-13 12:29:58 +08:00
    serco
        1
    serco  
       Feb 4, 2023   ❤️ 1
    不同的 trait 可以定义同名 method ,所以需要引入
    Lanterns
        2
    Lanterns  
       Feb 4, 2023 via Android
    因为你也可以在自己的库里为其实现自己的 Read
    RiverRay
        3
    RiverRay  
       Feb 5, 2023   ❤️ 1
    The reasoning for this is that multiple traits can define methods with the same name/signature.If this rule was not in place and there were multiple traits defining get for Read,

    Except for fully qualifying the method call, but that would also require you to import the trait!
    NetLauu
        4
    NetLauu  
       Jun 13, 2023
    the
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4264 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 00:56 · PVG 08:56 · LAX 17:56 · JFK 20:56
    ♥ Do have faith in what you're doing.