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

2023-02-04 18:19:26 +08:00
 liuser666

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 里已经有了吗?

1781 次点击
所在节点    Rust
4 条回复
serco
2023-02-04 18:32:33 +08:00
不同的 trait 可以定义同名 method ,所以需要引入
beloved70020
2023-02-04 19:42:51 +08:00
因为你也可以在自己的库里为其实现自己的 Read
RiverRay
2023-02-05 11:10:52 +08:00
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
325 天前
the

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/913182

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX