This lesson explains Type Inference in Rust and how it allows the compiler to figure out by itself, what type variables have when they get their values assigned.
There are cases when the compiler cannot infer a value's type through static analysis. In such cases, developers have to provide type annotations explicitly.
In many cases, Rust can infer the types from the code:
#[allow(warnings)]
fn main() {
let condition = false;
let some_number = 5;
let string_number = "5";
let names = ["Bob", "Alice", "Cindy"];
}
But some cases not:
let string_number = "5";
let number = string_number.parse().unwrap();
This is because parse().unwrap()
can be a string or number. So you need to tell the compiler what is the expected output.
let number: String = string_number.parse().unwrap(); // to string
let number: int32 = string_number.parse().unwrap(); // to int32
Another way is to use turbofish syntax
let number = string_number.parse::<String>().unwrap();
let number = string_number.parse::<int32>().unwrap();
标签:string,unwrap,number,parse,let,cases,Rust From: https://www.cnblogs.com/Answer1215/p/18021996