V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
liuser666
V2EX  ›  Rust

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

  •  1
     
  •   liuser666 · 2023-02-04 18:19:26 +08:00 · 1764 次点击
    这是一个创建于 440 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 条回复    2023-06-13 12:29:58 +08:00
    serco
        1
    serco  
       2023-02-04 18:32:33 +08:00   ❤️ 1
    不同的 trait 可以定义同名 method ,所以需要引入
    beloved70020
        2
    beloved70020  
       2023-02-04 19:42:51 +08:00 via Android
    因为你也可以在自己的库里为其实现自己的 Read
    RiverRay
        3
    RiverRay  
       2023-02-05 11:10:52 +08:00   ❤️ 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  
       311 天前
    the
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2962 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 03:20 · PVG 11:20 · LAX 20:20 · JFK 23:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.