2

I have following function:

    fn i_to_str(&self, i: int) -> &'a str {
        return i.to_string().as_slice();
    }

This code is producing error: borrowed value does not live long enough because of as_slice lifetime. Does anyone knows is there some workaround for this to make this possible?

user232343
  • 2,008
  • 5
  • 22
  • 34
  • 2
    A blog post of mine that explains what this sort of thing is all about: http://chrismorgan.info/blog/rust-fizzbuzz.html – Chris Morgan Oct 18 '14 at 02:54

1 Answers1

5

You cannot return a slice from this function, because the String returned by i.to_string() would be freed/dropped when exiting the function, and the slice would refer to a freed string. You should return a String instead (return i.to_string() directly in this case), or a MaybeOwned if the method is defined by a trait and some implementations could reasonably return a slice.

Francis Gagné
  • 60,274
  • 7
  • 180
  • 155