2

I'm trying to match an input to possible types, which will then convert that string value to a number. I have something like this:

fn letter_to_num(nameNum: &str) -> Option<f32> {
    match nameNum {
        Some(num) => {
            "One" => 1.0,
            "Two" => 2.0,
            "Three" => 3.0
        },
        None => println!("Invalid Number"),
    }
}

If it can't match the input, it'll return an error. Otherwise, it will match with one of the items and return Some(num) on success. I'm not entirely sure where to be putting the option statements and different combos seem to not want to compile either. The main error I'm getting is:

Expected one of '.', ',', ';', or an operator, found '=>'
pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
mbp12
  • 53
  • 1
  • 6

2 Answers2

3

First - you do matching on &str, not Option, so your code should look more like this.

fn letter_to_num(nameNum: &str) -> Option<f32> {
    match nameNum {
        "One" => Some(1.0),
        "Two" => Some(2.0),
        "Three" => Some(3.0),
        _ => None // or panic!("message")
    }
}

Key points here :

  • You need to match on &str values and return Option<f32>, not match on Option

  • You need to either return correct value from function (Some or None) or panic. println! neither panics nor returns correct type value. As a curiosity panics technically speaking never return to caller thus are allowed, they break execution of program.

  • When matching you need to specify exhausting set of matches, a wild card like _ will do. It basically says - match everything here. So you put it last. You could use a variable e.g. a here e.g. like this a => panic!("Invalid value {}", a)

Just some general remarks:

  • When comparing input consider upper case and lower case, you can achieve this by e.g. transforming input to lowercase and then matching, unless of course you only consider capitalized words as correct ones.
pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
GrayCat
  • 1,749
  • 3
  • 19
  • 30
2

The input is a &str, not Option<&str>, so Some(num) won't match nameNum's pattern. It should also renamed to be name_num, otherwise you will get warning about it. As you want to return an error message on strings that do not match, you could use Result.

fn letter_to_num(name_num: &str) -> Result<f32, &str> {
    match name_num {
        "One" => Ok(1.0),
        "Two" => Ok(2.0),
        "Three" => Ok(3.0),
        _ => Err("Invalid Number"),
    }
}

Test the code above on playground.

0x00A5
  • 1,462
  • 1
  • 16
  • 20