1

I found this code on 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...
}

Is the Rust compiler actually smart enough to infer that the type that the string holding the IP address should be parsed to is std::net::SocketAddr because the parsed variable is passed to the bind method which expects that type? Why don't you need to use the turbofish operator (::<>) or an explicit type annotation?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
jonathan-dev
  • 330
  • 1
  • 3
  • 16

1 Answers1

4

It is smart enough to use later usage of a variable to infer its type in the first place. The same could be seen in an extremely simple example:

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.
}

See also How does Rust's type inference work across multiple statements?

justinas
  • 6,287
  • 3
  • 26
  • 36