To convert a string to an i32 integer in Rust, you can use the parse
method that is available on any std::str::FromStr
type. Here's an example of how to do it:
main.rs120 chars6 lines
In this example, "42"
is a string literal. We then call the parse
method on this string by appending .parse::<i32>()
. The ::<i32>
part is a type hint to the compiler, telling it that we want to parse this string as an i32
integer. The unwrap
method is used to get the actual value out of the Result
type that parse
returns. After this conversion, my_int
will contain the value 42
.
Note that the parse
method returns a Result
type, which can represent either success (Ok
) or failure (Err
). In the example above, we simply call unwrap
to get the value out of the Ok
variant. However, in a real program, it is important to handle the Err
case gracefully.
gistlibby LogSnag