3 ms·
Aha. But what type does n.parse() have then, and how does the compiler derive it?
by amelius 1y ago
Aha. But what type does n.parse() have then, and how does the compiler derive it?
- ninkendo 1y agoThat function is returning a Vec<Token>, and so it knows the .collect() call needs to return a Vec<Token>, and so therefore the .map() function needs to return a Token. Therefore each match arm needs to return a Token too, so therefore the compiler selects the implementation of .parse() that returns Token. I admit when I started rust, seeing calls to .parse() was one of the more confusing things I saw in rust code, because of how much it leans on type inference to be readable. In places like these, it's a bit more readable: let ip: IpAddr = ip_str.parse()?; But when you see the .parse buried several levels deep and you have no idea what type it's trying to produce, it's a pain in the ass to read. This is why it's nice to use the turbo-fish syntax: let ip = ip_str.parse::<IpAddr>()?; Since you can drop .parse::<IpAddr>()? anywhere to make the type explicit, especially when buried in type-inferred blocks like the code in TFA.
- tialaramex 1y agoIn this case the compiler actually first wants the type for a parameter to the function Token::Operand That function is not shown, but it is included in the full source code which was linked. Well, technically we need to know that Rust says if there's a sum type Token::Operand which has an associated value, we can always call a function to make a Token::Operand with that value, and it just names this function Token::Operand too. So, Token::Operand takes an i32, a 32-bit signed integer. The compiler knows we're eventually getting an i32 to call this function, if not our program isn't valid. Which means n.parse().unwrap() has the type i32 We know n is an &str, the &str type has a generic function parse(), with the following signature: pub fn parse<F>(&self) -> Result<F, <F as FromStr>::Err> where F: FromStr So the type you now care about, that of n.parse() has to be Result of some kind, and we're going to call Result::unwrap() on that, to get an i32 This can only work if the type F in that generic signature above is i32 Which means the new type you care about was Result<i32, ParseIntError> and the parse function called will be the one which makes Ok(i32) when presented an in-range integer. Edited: Word-smithing, no significant change of meaning.