Hello, is it possible to do two actions when a matching occurs? As it is now my script runs as an indefinite loop.
Part of my code:
let input_string: i32 = match input_string.trim().parse() {
Ok(num) => num,
Ok(num) => break,
Err(_) => continue,
};
Here is my entire code, trouble begins at line 36 I think.
use std::io;
fn main() {
let mut celcius = 0.0;
let mut farenheit = 0.0;
let mut input_i32:i32 = 0;
println!("Please enter 0 for farenheit, 1 for celcius.");
input_i32 = read_input_line_i32();
if input_i32 == 1
{
println!("Converting from celcius to farenheit");
println!("Enter celcius")
} else {
println!("Converting from farenheit to celcius");
}
}
fn read_input_line_i32 () -> i32 {
let mut input_string = String::new();
loop {
println!("Enter number:");
io::stdin()
.read_line(&mut input_string)
.expect("Failed to read line");
let input_string: i32 = match input_string.trim().parse() {
Ok(num) => num,
Ok(num) => break,
Err(_) => continue,
};
}
let return_i32: i32 = input_string.parse::<i32>().unwrap();
return return_i32;
}
alice
July 6, 2021, 6:48pm
2
The way you do multiple things is as follows:
let input_string: i32 = match input_string.trim().parse() {
Ok(num) => {
println!("The first thing");
println!("The second thing");
// finally the expression that becomes the value of `input_string`
num
},
Err(_) => continue,
};
However in your case, you will need some additional restructuring to do what you wanted. The most direct fix seems to return early:
fn read_input_line_i32() -> i32 {
let mut input_string = String::new();
loop {
println!("Enter number:");
io::stdin()
.read_line(&mut input_string)
.expect("Failed to read line");
match input_string.trim().parse() {
Ok(num) => {
return num;
},
Err(_) => continue,
}
}
}
Unrelated, but I strongly encourage you to run your code through the rustfmt tool, which will automatically fix the indentation of your code.
1 Like
Looks to me like it builds . What is the error you're seeing?
Also note that the playground is a great resource when asking questions.
1 Like
visig
July 8, 2021, 10:46pm
4
In OP's code second match arm Ok(num) => break
are never reachable and cause a infinite loop.
Other thing I noticed is it try to parse()
twice, that are not necessary.
system
Closed
October 6, 2021, 10:46pm
5
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.