不使用直接在此源文件中使用的特性所需的`use`语句:为什么?(`use` statement necessary for trait not used directly in this source

编程入门 行业动态 更新时间:2024-10-27 08:25:32
不使用直接在此源文件中使用的特性所需的`use`语句:为什么?(`use` statement necessary for trait not used directly in this source file: why?)

在下面的代码中,删除第二行将导致编译错误说:

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.

更多推荐

本文发布于:2023-08-08 00:02:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466723.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:在此   所需   源文件   语句   特性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!