liuser666
V2EX  ›  Rust

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

  •  1
     
  •   liuser666 · Feb 4, 2023 · 3635 views
    This topic created in 1369 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
    serco
    Feb 4, 2023❤️1
    1
    不同的 trait 可以定义同名 method ,所以需要引入
    Lanterns
    Lanterns
    Feb 4, 2023 via Android
    2
    因为你也可以在自己的库里为其实现自己的 Read
    RiverRay
    RiverRay
    Feb 5, 2023❤️1
    3
    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
    NetLauu
    Jun 13, 2023
    4
    the
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   3349 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 10:17 · PVG 18:17 · LAX 02:17 · JFK 05:17
    ♥ Do have faith in what you're doing.