0

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?

1 Answer 1

5

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:

Sign up to request clarification or add additional context in comments.

3 Comments

So I got it working with fn name<'a>(&'a self) -> &'a str { let s: &'a str = self.name; s } is there any way for it work without the let binding?
I had in my memory that ~ to & conversioon worked, maybe was changed (or was always just for fuction parameters?), you have to just call as_slice
@cloudhead, for strings or owned vectors (~[T]) you have to call as_slice(). For other boxed types &*value should suffice. This will probably change when dynamically sized types land.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.