You can call str::parse(), but you need to make sure that read_line is working. We need a reader:

use std::io;

fn main() {
    let reader = io::stdin();
}

stdin reads the global buffer that handles the input stream and also implements the BufRead trait which has the read_line method method. This takes a mutable String as an input buffer and reads all bytes from the stream until a newline byte is reached and appends them to the buffer. The #expect() method unwraps the Result; if it is an Err it will panic with the message and the cause.

use std::io;

fn main() {
    let reader = io::stdin();
    let mut input_text = String::new();
    reader.read_line(&mut input_text).expect("failed to read line");
}

We now have the input text that we want to convert into an i32. This is where str::parse() will work for us, as long as we give it a type to parse to. str::trim() is necessary because read_line includes the newline byte the buffer

use std::io;

fn main() {
    let reader = io::stdin();
    let mut input_text = String::new();
    reader.read_line(&mut input_text).expect("failed to read line");
    let input = input_text.trim().parse::<i32>();
}

We're not done yet, we still need to ensure that we successfully parsed the input using pattern matching. All the code you need to convert your original input buffer into a usable integer is:

use std::io;

fn main() {
    let reader = io::stdin();
    let mut input_text = String::new();

    reader.read_line(&mut input_text).expect("failed to read line");

    let input_opt = input_text.trim().parse::<i32>();

    let input_int = match input_opt {
        Ok(input_int) => input_int,
        Err(e) => {
            println!("please input a number ({})", e);
            return;
        }
    };

    println!("{}", input_int);
}

This compiles without errors or warnings.

Answer from rouma7 on Stack Overflow
Top answer
1 of 5
19

You can call str::parse(), but you need to make sure that read_line is working. We need a reader:

use std::io;

fn main() {
    let reader = io::stdin();
}

stdin reads the global buffer that handles the input stream and also implements the BufRead trait which has the read_line method method. This takes a mutable String as an input buffer and reads all bytes from the stream until a newline byte is reached and appends them to the buffer. The #expect() method unwraps the Result; if it is an Err it will panic with the message and the cause.

use std::io;

fn main() {
    let reader = io::stdin();
    let mut input_text = String::new();
    reader.read_line(&mut input_text).expect("failed to read line");
}

We now have the input text that we want to convert into an i32. This is where str::parse() will work for us, as long as we give it a type to parse to. str::trim() is necessary because read_line includes the newline byte the buffer

use std::io;

fn main() {
    let reader = io::stdin();
    let mut input_text = String::new();
    reader.read_line(&mut input_text).expect("failed to read line");
    let input = input_text.trim().parse::<i32>();
}

We're not done yet, we still need to ensure that we successfully parsed the input using pattern matching. All the code you need to convert your original input buffer into a usable integer is:

use std::io;

fn main() {
    let reader = io::stdin();
    let mut input_text = String::new();

    reader.read_line(&mut input_text).expect("failed to read line");

    let input_opt = input_text.trim().parse::<i32>();

    let input_int = match input_opt {
        Ok(input_int) => input_int,
        Err(e) => {
            println!("please input a number ({})", e);
            return;
        }
    };

    println!("{}", input_int);
}

This compiles without errors or warnings.

2 of 5
8

The input includes a newline at the end, as explained in the documentation for read_line. This causes from_str() to fail. Using std::str::trim() and changing this:

let input: Result<i32, _> = input_text.parse();

into this:

let input: Result<i32, _> = input_text.trim().parse();

seems to work.

๐ŸŒ
W3Resource
w3resource.com โ€บ rust-tutorial โ€บ rust-string-to-int.php
Rust string to integer conversion with Examples
fn main() { // Convert a string to a 64-bit integer let large_number: i64 = "9223372036854775807".parse().unwrap(); // i64 max value println!("Large number: {}", large_number); } ... Converts a string slice (&str) into a number.
๐ŸŒ
Rust Programming Language
users.rust-lang.org โ€บ help
Split string and convert to integer - help - The Rust Programming Language Forum
October 11, 2021 - I'm starting with Rust. I have the following code, which works well, but I see it quite ugly. How can I improve this? What I try to get is the value after: as an integer "user:2" in this case the number 2 fn main() { let port_data: &str = "user:2"; let data: Vec ().unwrap_or(0); printl...
๐ŸŒ
DEV Community
dev.to โ€บ sharmaprash โ€บ how-to-convert-a-string-to-an-integer-in-rust-1f0n
how to convert a String to an Integer in Rust - DEV Community
March 12, 2024 - Converting a string to an integer in Rust is straightforward using the parse() method. Remember to handle potential parsing errors appropriately to ensure the robustness of your code.
๐ŸŒ
The Rust Programming Language
doc.rust-lang.org โ€บ book โ€บ ch04-03-slices.html
The Slice Type - The Rust Programming Language
So, in the case of let world = &s[6..11];, world would be a slice that contains a pointer to the byte at index 6 of s with a length value of 5. Figure 4-7 shows this in a diagram. Figure 4-7: A string slice referring to part of a String
๐ŸŒ
CopyProgramming
copyprogramming.com โ€บ howto โ€บ convert-string-slice-to-int-in-rust
String: Converting a Rust string slice to an integer
July 11, 2023 - How do I convert from an integer to a string?, You're right; to_str() was renamed to to_string() before Rust 1.0 was released for consistency because an allocated string is now called String. If you need to pass a string slice somewhere, you need to obtain a &str reference from String.This can ...
Find elsewhere
๐ŸŒ
Dot Net Perls
dotnetperls.com โ€บ parse-rust
Rust - parse Examples: Convert String to Integer - Dot Net Perls
We can use the special Rust TurboFish operator in an if-let statement to parse to a usize. Detail With parse(), we can unwrap() the result. But using if let Ok() is a more elegant and clean syntax for parse. fn main() { let data = "1200"; // Parse to a specific type with TurboFish. if let Ok(result) = data.parse::<usize>() { println!("USIZE RESULT: {}", result); } } ... Suppose we have some digits inside of another string. We can extract a slice from the string with a function like get().
๐ŸŒ
Rust By Example
doc.rust-lang.org โ€บ rust-by-example โ€บ conversion โ€บ string.html
To and from Strings - Rust By Example
It's useful to convert strings into many types, but one of the more common string operations is to convert them from string to number. The idiomatic approach to this is to use the parse function and either to arrange for type inference or to specify the type to parse using the 'turbofish' syntax.
๐ŸŒ
Linux Hint
linuxhint.com โ€บ rust-string-to-int
How to Convert String to Int Using Rust โ€“ Linux Hint
To convert a string to an int in Rust, we can use the parse function to convert a string to an int in the Rust language.
๐ŸŒ
Rust Programming Language
users.rust-lang.org โ€บ help
How to parse an int from string? - help - The Rust Programming Language Forum
August 20, 2017 - let string = "Rust4Fun"; assert_eq!(4, string.parse_int()); I want to get the int from the string as above, so could you give me some tips to implement the parse_int() method?
๐ŸŒ
mkaz.blog
mkaz.blog โ€บ working-with-rust โ€บ numbers
Numbers - mkaz.blog
Either specify the float type to ... let str = "2.71828"; let e = str.parse::<f32>().unwrap(); To convert a single char to an integer in Rust, use .to_digit(RADIX)....
๐ŸŒ
RustJobs.dev
rustjobs.dev โ€บ blog โ€บ convert-string-to-int-in-rust
Converting a String to int in Rust | RustJobs.dev
September 8, 2023 - Converting a String to an int in Rust is straightforward using the parse() method.
๐ŸŒ
Reddit
reddit.com โ€บ r/rust โ€บ parsing an int from a &str
r/rust on Reddit: Parsing an int from a &str
August 29, 2012 -

Is this really the only way to get a &str into an int?

int::parse_bytes("10".to_string().into_bytes().as_slice(), 10)

It seems a little ridiculous that one has to turn it into a String, then Vec<u8>, then &[u8]. Maybe this is a lack of documentation but I feel like there must be a more straightforward method.

๐ŸŒ
MIT
web.mit.edu โ€บ rust-lang_v1.25 โ€บ arch โ€บ amd64_ubuntu1404 โ€บ share โ€บ doc โ€บ rust โ€บ html โ€บ book โ€บ second-edition โ€บ ch04-03-slices.html
Slices - The Rust Programming Language
Internally, the slice data structure stores the starting position and the length of the slice, which corresponds to ending_index minus starting_index. So in the case of let world = &s[6..11];, world would be a slice that contains a pointer to the 6th byte of s and a length value of 5. Figure 4-6 shows this in a diagram. Figure 4-6: String slice referring to part of a String ยท With Rustโ€™s ..
๐ŸŒ
Wduquette
wduquette.github.io โ€บ parsing-strings-into-slices
Parsing Rust Strings into Slices
The Chars iterator can return a &str slice containing the remainder of the source string. Itโ€™s easy to compute a slice from two slices one of which completely contains the other. For the record, I found the solution at users.rust-lang.org.
๐ŸŒ
Javaer101
javaer101.com โ€บ en โ€บ article โ€บ 12385295.html
Convert string slice to int in Rust - Javaer101
use std::io; fn main() { let reader = io::stdin(); let mut input_text = String::new(); reader.read_line(&mut input_text).expect("failed to read line"); let input_opt = input_text.trim().parse::<i32>(); let input_int = match input_opt { Ok(input_int) => input_int, Err(e) => { println!("please input a number ({})", e); return; } }; println!("{}", input_int); }