EDIT: It turns out that the Rust compiler is not smart enough to carry over information about whether or not a variable was statically defined. At the point when you pattern match, the compiler only knows that its a String.
I am trying to make a parser in Rust and I have already defined a Token
enum as so.
pub enum Constant {
String(String),
}
pub enum Token {
KwIf,
KwThen,
KwElse,
Constant(Constant),
}
I have also written a literal
function, the important bit is that this function returns static strings (i.e. &'static str
), because of performance reasons (the strings will also never change so it makes sense for them to be constant throughout the lifetime of the program).
impl Token {
pub fn literal(&self) -> Option<&'static str> {
match self {
&Token::KwIf => Some("if"),
&Token::KwThen => Some("then"),
&Token::KwElse => Some("else"),
_ => None,
}
}
}
The issue I have right now is how would you pattern match against the literal
function and use the rust print!
function to directly print the literal string, i.e. assuming I write something like this
use Constant::*;
pub fn print_token(token: Token) {
match token.literal() {
Some(literal) => print!(literal);
None => match token {
Token::Constant(constant) => match constant {
String(string) => print!("{}", string),
_ => panic!("Unexpected token"),
}
}
}
}
The issue is that I get a compile error when I try to print this literal, i.e. the compile error I get is error: format argument must be a string literal.
I have tried many combinations of how to print the static string literal without having to cast it to a normal String
(which of course defeats the purpose of using a static string literal in the first place).
Alternately is there a better way to approach the problem I am trying to solve, I am making a parser for a language and as can be soon, I am coding up the tokens as well parser/printer.