BARNOWL
BARNOWL

Reputation: 3599

Error when using match, expected struct string, but found &str when using match

I'm getting the below error when using match.

"add" => { | ^^^^^ expected struct String, found &str

match input_string { | ------------ this expression has type String 22 | "add" => { | ^^^^^ expected struct String, found &str

I'm not exactly sure how to resolve this.

Ideally, rust will prompt user to enter either add, subtract, etc.

It should be followed by the match statement.

use std::io;

fn add(x1: i32, x2: i32) -> i32 {
    return x1 + x2;
}
fn subtract(x1: i32, x2: i32) -> i32 {
    return x1 - x2;
}
fn multiply(x1: i32, x2: i32) -> i32 {
    return x1 * x2;
}
fn divide(x1: i32, x2: i32) -> i32 {
    return x1 / x2;
}

fn main() {
    let mut input_string = String::new();
    println!("Enter either add, substract, multiply, or divide:");
    io::stdin().read_line(&mut input_string).unwrap();

    match input_string {
        "add" => {
            let mut input_number = String::new();

            io::stdin()
                .read_line(&mut input_number)
                .expect("Not a valid string");

            println!("Number 1 {}", input_number);
            let mut input_number2 = String::new();
            io::stdin()
                .read_line(&mut input_number2)
                .expect("Not a valid string");

            println!("Number 2 {}", input_number2);

            let parsedNumb1: i32 = input_number.trim().parse().unwrap();
            let parsedNumb2: i32 = input_number2.trim().parse().unwrap();
            add(parsedNumb1, parsedNumb2);
        }
    }
}

Rust playground

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c9387928038a5b21559cb1791a731184

Upvotes: 1

Views: 509

Answers (2)

Silvio Mayolo
Silvio Mayolo

Reputation: 70377

Borrow the String as a &str using String::as_str

match input_string.as_str() {
  "add" => {
    ...
  }
  ...
}

You can get the same result with the old borrow-unborrow trick to trigger a deref, but most people (myself included) find that unreadable and confusing.

match &*input_string {
  "add" => {
    ...
  }
  ...
}

Upvotes: 2

Unmitigated
Unmitigated

Reputation: 89497

A string literal like "add" has type &str, which can't be directly matched against a value of type String. You can use .as_str() to get a string slice from the String. To get the word to match exactly, you will also need to remove the newline in input_string, which can be done with .trim_end().

match input_string.as_str().trim_end() {

Alternatively, it is sufficient to just match on the result of trim_end() as it returns a string slice:

match input_string.trim_end() {

After these modifications, you need to add a catchall case so that the match is exhaustive, e.g.

c => println!("Invalid command: {c}")

Upvotes: 3

Related Questions