3 ms·
parse() is generic over it's return type (which is Result<F, F::Err> where F: FromStr) [1]. The value of which can be inferred. The result of parse().unwrap()
by Coding_Cat 10y ago
parse() is generic over it's return type (which is Result<F, F::Err> where F: FromStr) [1]. The value of which can be inferred.
The result of parse().unwrap() is of type F, which means addr is of type 'F'. afterwards when we call `let sock = TcpListener::bind(&addr, &handle).unwrap();` the compiler can infer from the signature of `TcpListener::bind`[2] what F has to be, namely `std::net::SocketAddr`
[1] https://doc.rust-lang.org/std/primitive.str.html https://doc.rust-lang.org/std/primitive.str.html
[2] https://tokio-rs.github.io/tokio-core/tokio_core/net/struct.TcpListener.html https://tokio-rs.github.io/tokio-core/tokio_core/net/struct....
- koolba 10y agoWhere is string to address parse implementation defined? I took a peek at SocketAddr and see a from_str function. Does that name have special significance?
- steveklabnik 10y agoIt's at the very bottom of https://doc.rust-lang.org/std/net/enum.SocketAddr.html https://doc.rust-lang.org/std/net/enum.SocketAddr.html, the part that says impl FromStr for SocketAddr If you look at parse https://doc.rust-lang.org/std/primitive.str.html#method.parse https://doc.rust-lang.org/std/primitive.str.html#method.pars... it says fn parse<F>(&self) -> Result<F, F::Err> where F: FromStr So any type that implements FromStr can be parse'd from a &str.
- amichal 10y agowhich has a link to the actual src which is here-ish and is what you might expect https://doc.rust-lang.org/src/std/up/src/libstd/net/parser.rs.html#298 https://doc.rust-lang.org/src/std/up/src/libstd/net/parser.r...
- winstonewert 10y agoIf you look closely, you'll see that the from_str function is part of the implementation of the FromStr trait for the SocketAddr struct. Its this FromStr trait that the parse() method depends on.
- ucarion 10y agoThe method `from_str` is from the FromStr trait. [1] The `parse` function only works on types that implement FromStr. It's "special" in that it's the conventional way to do things, but the compiler does not treat FromStr specially. [1]: https://doc.rust-lang.org/std/str/trait.FromStr.html https://doc.rust-lang.org/std/str/trait.FromStr.html