Discussion:
[rust-dev] Help needed with lifetimes.. (I'm new to rust)
Jake Scott
2014-10-20 19:57:43 UTC
Permalink
Can someone give me a hand, I'm getting the following lifetime error:

error: clean_number does not live long enough

Short url: http://is.gd/VIzHMS

This is the code:

#![feature(phase)]
#[phase(plugin)]

extern crate regex_macros;
extern crate regex;

use regex::Regex;

static ALPHA_REGEX: Regex = regex!(r"[a-zA-Z]");
static NUMBER_REGEX: Regex = regex!(r"[^0-9]");

fn main() {
let number = number("ads(123) 456-7890");
println!("{}", number);
}

fn number<'a>(number: &'a str) -> &'a str {
let clean_number = clean(number);
clean_number
}

fn clean<'a>(number: &'a str) -> &'a str {
if ALPHA_REGEX.is_match(number) {
"0000000000";
}
let clean_number: String = NUMBER_REGEX.replace(number, "");
return clean_number.as_slice();
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20141021/b00f2bc8/attachment.html>
Clark Gaebel
2014-10-20 20:02:46 UTC
Permalink
`clean_number` inside the function `clean` is destructed, and a slice into the destructed String is returned. You?re probably looking for the `MaybeOwned` enum in the standard library to do what you want:





http://is.gd/QvkESn




Regards,

? - Clark
Post by Jake Scott
error: clean_number does not live long enough
Short url: http://is.gd/VIzHMS
#![feature(phase)]
#[phase(plugin)]
extern crate regex_macros;
extern crate regex;
use regex::Regex;
static ALPHA_REGEX: Regex = regex!(r"[a-zA-Z]");
static NUMBER_REGEX: Regex = regex!(r"[^0-9]");
fn main() {
let number = number("ads(123) 456-7890");
println!("{}", number);
}
fn number<'a>(number: &'a str) -> &'a str {
let clean_number = clean(number);
clean_number
}
fn clean<'a>(number: &'a str) -> &'a str {
if ALPHA_REGEX.is_match(number) {
"0000000000";
}
let clean_number: String = NUMBER_REGEX.replace(number, "");
return clean_number.as_slice();
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/rust-dev/attachments/20141020/b5a11e68/attachment.html>
comex
2014-10-20 22:02:40 UTC
Permalink
Post by Jake Scott
fn clean<'a>(number: &'a str) -> &'a str {
if ALPHA_REGEX.is_match(number) {
"0000000000";
}
let clean_number: String = NUMBER_REGEX.replace(number, "");
return clean_number.as_slice();
}
FYI, this doesn't do what you think it does. "0000000000"; just
throws away a string - I don't know why the warning for it isn't
enabled by default. You could either use "return" or change it to
if/else:

if ALPHA_REGEX.is_match(number) {
"0000000000" // no semicolon
} else {
...
}

Loading...