liuser666
V2EX  ›  Rust

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

  •  1
     
  •   liuser666 · Feb 4, 2023 · 3079 views
    This topic created in 1197 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   ·   3110 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 58ms · UTC 03:16 · PVG 11:16 · LAX 20:16 · JFK 23:16
    ♥ Do have faith in what you're doing.