0

I am working on a Reverse Polish Notation problem. In the eval function, I want to pass the input tokens as a reference, then iterate through it and using match to do something either A or B. But the program produces an error:

expected reference, found enum main::Token.

I want to check the type of token here, but Rust doesn't seem to have a straightforward way to print out the type. What is the error source here?

pub enum Operator {
    // `+`
    Add, 
    // `-`
    Sub,
    // `*`
    Mul,
}

pub enum Token {
    Operator(Operator),
    Operand(isize),
}

pub fn eval(tokens: &[Token]) -> Option<isize> {       
    for token in tokens {
        // error here: expected reference, found enum `main::Token` 
        match token {
            Token::Operator(ref a) => println!("do something A"),
            Token::Operand(ref b) => println!("do something B"),
        };
    } 

    Some(5) 
}

fn main() { 
    // test input
    let input1 = Token::Operand(3);
    let input2 = Token::Operand(2);
    let sign1 = Operator::Add;
    let input3 = Token::Operator(sign1);
    eval(&[input1, input2, input3]);
}

My question is not a duplicate of Matching on a reference to an enum, since add ref doesn't save it from the type mismatch error.

Community
  • 1
  • 1
enaJ
  • 1,565
  • 5
  • 16
  • 29
  • 2
    Additional info: when you're iterating through a `&[Token]`, the yielded items are references, not the values directly. Therefore `token` in your `for`-loop has the type `&main::Token` which is different from `main::Token`. – Lukas Kalbertodt Oct 16 '16 at 17:26
  • 1
    And [How do I print the type of a variable in Rust?](http://stackoverflow.com/q/21747136/155423). – Shepmaster Oct 16 '16 at 17:27
  • @LukasKalbertodt, thanks that makes lots of sense, but if I use Token::Operator(ref a) => println!("do something A"), still not work. Any suggestion? – enaJ Oct 16 '16 at 17:37
  • 3
    `token` has `&Token` type, and you're trying to match it as `Token` type. Use `match *token`, as suggested in the duplicate's answer. Using `ref` in a pattern only alters type of the variable inside the corresponding branch, but has no effect on the `match` itself. – Pavel Strakhov Oct 16 '16 at 17:47
  • @PavelStrakhov, that really helps!!! – enaJ Oct 16 '16 at 18:24
  • @PavelStrakhov, does (ref a) and (& a) has the same meaning? Why I cannot use Token::Operator(& a) => println!("do something A")? – enaJ Oct 16 '16 at 18:31
  • @enaJ: http://stackoverflow.com/a/33204483/234590 – Francis Gagné Oct 16 '16 at 22:01

0 Answers0