Returning a string from a method in Rust
-
21-12-2019 - |
Question
Editor's note: The syntax in this question predates Rust 1.0 and the 1.0-updated syntax generates different errors, but the overall concepts are still the same in Rust 1.0.
I have a struct T with a name
field, I'd like to return that string from the name
function. I don't want to copy the whole string, just the pointer:
struct T {
name: ~str,
}
impl Node for T {
fn name(&self) -> &str { self.name }
// this doesn't work either (lifetime error)
// fn name(&self) -> &str { let s: &str = self.name; s }
}
trait Node {
fn name(&self) -> &str;
}
Why is this wrong? What is the best way to return an &str
from a function?
Solution
You have to take a reference to self.name
and ensure that the lifetimes of &self
and &str
are the same:
struct T {
name: String,
}
impl Node for T {
fn name<'a>(&'a self) -> &'a str {
&self.name
}
}
trait Node {
fn name(&self) -> &str;
}
You can also use lifetime elision, as shown in the trait definition. In this case, it automatically ties together the lifetimes of self
and the returned &str
.
Take a look at these book chapters:
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow