In Rust, converting the character '1' to the integer 1 can be achieved using the to_digit method, which is part of the char type. This method accepts a radix parameter; for decimal conversion, the radix must be 10.
Here is a simple example:
rustfn main() { let c = '1'; if let Some(num) = c.to_digit(10) { println!("Character '{}' corresponds to integer {}", c, num); } else { println!("Character '{}' cannot be converted to an integer.", c); } }
In this example:
- A variable named
cis created that holds the character'1'. c.to_digit(10)is used to attempt converting the character to anOption<u32>integer, where 10 is the radix (since we are converting decimal digits).- The
to_digitmethod returns anOption<u32>, containingSome(value)on successful conversion andNoneif the character is not a valid digit. - The
if letconstruct is employed to check the result ofto_digitand handle it accordingly.
The to_digit method is highly versatile, as it supports conversions for digits beyond decimal (e.g., hexadecimal or octal) by simply adjusting the radix value passed to it.
Another approach involves directly computing the difference between the char value and the character '0' to obtain the equivalent numeric value. For example:
rustfn main() { let c = '1'; let num = c as u32 - '0' as u32; println!("Character '{}' corresponds to integer {}", c, num); }
Here, the character '1' and '0' are explicitly converted to u32 and their difference is calculated to derive the corresponding integer. This method is limited to ASCII characters and assumes the character represents a digit between 0 and 9.