< 返回版块

zhylmzr 发表于 2020-11-24 18:06

Tags:syntax

pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
    super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
}

在这里TcpListener是一个struct,map的参数签名是F: FnOnce(T) -> U,它怎么可以作为map的参数呢?

评论区

写评论
作者 zhylmzr 2020-11-24 19:42

又学到了新知识点😄tuple struct可以直接作为函数使用

--
👇
whfuyn: ``` #[stable(feature = "rust1", since = "1.0.0")] pub struct TcpListener(net_imp::TcpListener);

这个是`TcpListener`的定义,它在这里被用作构造函数。

我没找到哪里有说`tuple struct`的`constructor`实现了`FnOnce`,不过这里有一段可以看一下:

https://doc.rust-lang.org/stable/reference/expressions/struct-expr.html

Tuple struct expression

A struct expression with fields enclosed in parentheses constructs a tuple struct. 
Though it is listed here as a specific expression for completeness, it is equivalent to a call expression to the tuple struct's constructor. 
whfuyn 2020-11-24 18:35
#[stable(feature = "rust1", since = "1.0.0")]
pub struct TcpListener(net_imp::TcpListener);

这个是TcpListener的定义,它在这里被用作构造函数。

我没找到哪里有说tuple structconstructor实现了FnOnce,不过这里有一段可以看一下:

https://doc.rust-lang.org/stable/reference/expressions/struct-expr.html

Tuple struct expression

A struct expression with fields enclosed in parentheses constructs a tuple struct. Though it is listed here as a specific expression for completeness, it is equivalent to a call expression to the tuple struct's constructor.

songzhi 2020-11-24 18:13

因为TcpListener的类型是struct TcpListener(net_imp::TcpListener);,所以你就把它名字当成构造函数理解就完了。具体在Rust里面这叫什么概念我也忘了。

1 共 3 条评论, 1 页