我在the tokio hello world page上找到了这段代码:
fn main() {
let addr = "127.0.0.1:6142".parse().unwrap();
let listener = TcpListener::bind(&addr).unwrap();
// Following snippets come here...
}
Rust编译器实际上是否足够聪明,可以推断出包含IP地址的字符串应解析为的类型为std::net::SocketAddr
,因为已解析的变量已传递给需要该类型的bind方法?为什么不需要use the turbofish operator (::<>) or an explicit type annotation?
答案 0 :(得分:4)
足够聪明,可以首先使用变量的后续用法来推断其类型。在一个非常简单的示例中可以看到相同的结果:
fn foo(v: Vec<i16>) {
println!("{:?}", v);
}
fn main() {
let mut numbers = vec![]; // Let's make a Vec<_>
numbers.push(12345); // Let's push a number (of an unknown type) to it
foo(numbers); // A-ha! It is passed to a function requiring a Vec<i16>.
// That means `numbers` is Vec<i16>
// and the constant 12345 is of type i16.
}
另请参见How does Rust's type inference work across multiple statements?