在下面的代码中,删除第二行将导致编译错误说:
type `std::io::net::tcp::TcpListener` does not implement any method in scope named `listen`由于我无处直接使用Listener(即使std在内部使用它),为什么我需要指定它?
use std::io::{TcpListener, TcpStream}; use std::io::{Acceptor, Listener}; fn handle_client(mut stream: TcpStream) { // ... } fn main() { let args = std::os::args(); println!("{}", args); let listener = TcpListener::bind("127.0.0.1", 80).unwrap(); let mut acceptor = listener.listen().unwrap(); for stream in acceptor.incoming() { spawn(proc() { handle_client(stream.unwrap()); }); } }In the code below, removing the second line will result in a compilation error saying:
type `std::io::net::tcp::TcpListener` does not implement any method in scope named `listen`Since I am nowhere directly using Listener (even though std uses it internally), why do I need to specify it?
use std::io::{TcpListener, TcpStream}; use std::io::{Acceptor, Listener}; fn handle_client(mut stream: TcpStream) { // ... } fn main() { let args = std::os::args(); println!("{}", args); let listener = TcpListener::bind("127.0.0.1", 80).unwrap(); let mut acceptor = listener.listen().unwrap(); for stream in acceptor.incoming() { spawn(proc() { handle_client(stream.unwrap()); }); } }最满意答案
要求明确use实现方法的特征是语言的设计决策。 例如,在以下代码中:
use my::A; use my::B; mod my { pub trait A { fn foo(&self); } pub struct B; impl B { pub fn bar(&self) { println!("Called `bar`."); } } impl A for B { fn foo(&self) { println!("Called `foo`."); } } } fn main() { // Requires "use my::B". let b = B; b.bar(); // Requires "use my::A". b.foo(); }我认为这样做的动机很大程度上是由于目前没有无缝的方法来支持具有相同方法名称的多个特征。 然而,有很多工作要做特质, 请访问https://github.com/rust-lang/rfcs/blob/master/active/0024-traits.md 。
It was a design decision of the language to require explicit use of traits that implement methods. For example in the following code:
use my::A; use my::B; mod my { pub trait A { fn foo(&self); } pub struct B; impl B { pub fn bar(&self) { println!("Called `bar`."); } } impl A for B { fn foo(&self) { println!("Called `foo`."); } } } fn main() { // Requires "use my::B". let b = B; b.bar(); // Requires "use my::A". b.foo(); }I believe the motivation for this is heavily due to the fact that currently there is no seamless way to support multiple traits with the same method name. There is a lot of work being done to traits atm however https://github.com/rust-lang/rfcs/blob/master/active/0024-traits.md.
更多推荐
发布评论