Given that I've got a struct that contains a string, I'd like to add a method that returns an immutable reference to the string. In the simple case, this works:
struct MyVal {
string: String,
}
impl MyVal {
fn get(&self) -> &str { &self.string }
}
Fair enough. Now, in my case the string may or may not be present; but suppose it is. (Yeah, I know that calling "unwrap()" like this is bad style. Bear with me.)
struct MyVal {
string: Option<String>,
}
impl MyVal {
// Doesn't work; temporary value created.
fn get(&self) -> &str { &self.string.unwrap().string }
}
The reason why I've got that Option in there is because the string isn't always present; but it can be created on the fly when it's needed using internal mutability, so it will always actually exist when I want it:
struct MyVal {
string: RefCell<Option<String>>,
}
impl MyVal {
// Doesn't work; temporary value created.
fn get(&self) -> &str {
// Omitted: ensure sure the string is_some
// I might not have the syntax quite right for the RefCell, but it doesn't matter
// because I still have a temporary value.
&self.string.borrow().unwrap().string
}
}
In my actual code I work around this by using RefCell<Option<Rc<String>>>
and
explicitly returning Rc<String>
, which works well enough; but I'd rather not leak the presence of Rc
and just return &str
.
It seems like it ought to be doable; the MyVal struct owns the value, and should be able to return an immutable borrow to it, but I don't know how.