Convert string to (integer) number - parse, turbofish
-
i32
-
parse
-
expect
-
::<>()
-
In the printing we won't see the difference, but we can do numberical operations on numbers.
-
We can either define the expect type next to the variable name where we are assigning to.
-
Or we can use the so-called turbofish operator
::<>()
as we do in the second example.
fn main() { let text = "23"; println!("{text:?}"); println!(); let number: i32 = text.parse().unwrap(); println!("{number}",); println!("{}", number + 1); println!(); let number = text.parse::<i32>().expect("Could not convert to i32"); println!("{number}",); println!("{}", number + 1); let text = "3.14"; let number = text.parse::<i32>().unwrap(); //.expect("Could not convert to i32"); println!("{number}",); }
"23"
23
24
23
24