Hello!
I'm new to Rust and I came across the issue E0515.
Here's my code below.
fn makenumber<'a>(&mut self) -> Token<'a> {
let mut num: String = "".to_string();
let mut dots = 0;
let start = self.pos.copy();
while (! self.end) && (DIGITS.to_string() + ".").contains(self.ch) {
if self.ch == '.' {
if dots >= 1 {break}
dots += 1;
num += ".";
} else {
num += self.ch.to_string().as_str();
}
self.advance();
}
self.retreat();
if self.ch != '.' {
self.advance()
}
if dots == 0 {
return Token {token: TT_INT, value: num.as_str(), start: start, end: self.pos.copy()}
} else {
return Token {token: TT_FLOAT, value: num.as_str(), start: start, end: self.pos.copy()}
}
}
The error was on the lines
return Token {token: TT_INT, value: num.as_str(), start: start, end: self.pos.copy()}
// and
return Token {token: TT_FLOAT, value: num.as_str(), start: start, end: self.pos.copy()}
The error said 'cannot return value referencing local variable `num
`'. How can I fix this?
Here is my Token
struct & implementation code:
#[derive(Clone)]
pub struct Token<'a> {
pub token : &'a str,
pub value : &'a str,
pub start : lexer::LexerPosition,
pub end : lexer::LexerPosition
}
impl fmt::Display for Token<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let tokenname: ColoredString;
if [TT_EOL, TT_EOF].contains(&self.token) {
tokenname = self.token.truecolor(68, 73, 75);
} else if [TT_EQUALEQ, TT_NOTEQ, TT_LSSTHN, TT_LSSTHNEQ, TT_GRTTHN, TT_GRTTHNEQ].contains(&self.token) {
tokenname = self.token.truecolor(192, 0, 0);
} else if [TT_INT, TT_FLOAT, TT_STRING].contains(&self.token) {
tokenname = self.token.truecolor(0, 192, 0);
} else if [TT_PLUS, TT_MINUS, TT_TIMES, TT_DIVBY, TT_POW, TT_SQRT, TT_CAST].contains(&self.token) {
tokenname = self.token.truecolor(157, 128, 0);
// Blue
} else if [TT_PLUSEQ, TT_MINUSEQ, TT_TIMESEQ, TT_DIVBYEQ, TT_POWEQ, TT_SQRTEQ].contains(&self.token) {
tokenname = self.token.truecolor(174, 64, 0);
} else if [TT_EQUALS].contains(&self.token) {
tokenname = self.token.truecolor(0, 255, 255);
} else {
tokenname = self.token.normal()
}
if self.value.len() >= 1 {
let tokenvalue: ColoredString;
if [TT_INT, TT_FLOAT].contains(&self.token) {
tokenvalue = self.value.truecolor(181, 206, 168);
} else if [TT_STRING].contains(&self.token) {
tokenvalue = format!("`{}`", self.value.truecolor(206, 145, 145)).normal();
} else {
tokenvalue = self.value.normal();
}
write!(f, "{}", format!("<{}: {}>", tokenname, tokenvalue))
} else {
if self.token == TT_EOL {
write!(f, "<{}>\n", tokenname)
} else {
write!(f, "<{}>", tokenname)
}
}
}
}