Home > Mobile >  If else statements with string comparisons in Rust?
If else statements with string comparisons in Rust?

Time:07-07

Just starting with rust and trying to build a simple calculator that takes in a number, then an operator, and then another number. I have this function that is supposed to return answer to the equation.

fn equation(num1: i64, op: String, num2: i64) -> i64{
    if op.eq(" "){
        num1 num2
    } else if op.eq("-"){
        num1-num2
    } else if op.eq("*"){
        num1*num2
    } else if op.eq("/"){
        num1/num2
    } else{
        0
    }
}

The problem is, it returns 0 every time. However, if instead of comparing a string, I use an integer where 1 is , 2 is -, 3 is * and 4 is /, it works fine

fn equation(num1: i64, op: i64, num2: i64) -> i64{
    if op == 1{
        num1 num2
    } else if op == 2{
        num1-num2
    } else if op == 3{
        num1*num2
    } else if op == 4{
        num1/num2
    } else{
        0
    }
}

^^ This returns the correct solution without any issues, can anyone tell me what I'm doing wrong here? Here is what my whole project looks like in case the issue lies elsewhere

use std::io;

fn main() {
    let mut num1 = String::new();
    println!("Enter your first number:");

    io::stdin()
        .read_line(&mut num1)
        .expect("Failed to enter number.");
    
    let num_1: i64 = num1.trim().parse::<i64>().unwrap();
    //let num_1: i64 = num1.trim().parse().expect("figure out whats happening here");
    println!("{num1}");


    println!("Enter your operator (  - * /):");
    let mut op = String::new();

    io::stdin()
        .read_line(&mut op)
        .expect("failed to enter operator.");

    let mut num2 = String::new();
    println!("Enter your second number:");

    io::stdin()
        .read_line(&mut num2)
        .expect("Failed to enter numbers.");

    let num_2 = num2.trim().parse::<i64>().unwrap();

    println!("Your answer: {}", equation(num_1, op, num_2));

}
fn equation(num1: i64, op: String, num2: i64) -> i64{
    if op.eq(" "){
        num1 num2
    } else if op.eq("-"){
        num1-num2
    } else if op.eq("*"){
        num1*num2
    } else if op.eq("/"){
        num1/num2
    } else{
        0
    }
}

CodePudding user response:

It seems that the problem is that you are expecting a "String" as the second parameter in the equation function as opposed to a "&str" which is different in the Rust language. The link below is a good reference to see the difference between the two. Happy coding!

What are the differences between Rust's `String` and `str`?

CodePudding user response:

Your forgot to trim the newline character in op

println!("Your answer: {}", equation(num_1, op.trim().to_string(), num_2));
$ cargo run -q
Enter your first number:
1
1

Enter your operator (  - * /):
 
Enter your second number:
2
Your answer: 3
  • Related