Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Struct storing and returning shared vs. mutable references
Heya!
(First post, please be kind)
I am - desperately - trying to understang why Case 1 works
pub struct Thing<'a> {
data: &'a Data,
}
impl<'a> Thing<'a> {
pub fn get(&self) -> &'a Data {
self.data
}
}
But Case 2 doesn't:
pub struct Thing<'a> {
data: &'a mut Data,
}
impl<'a> Thing<'a> {
pub fn get(&mut self) -> &'a mut Data {
self.data
}
}
Using common-sense, my conclusion is as follows
Case 1:
Case 2:
Now I am wondering how Rust thinks about this & accepts Case 1 but comes to the conclusion that Case 2 can cause problems:
22 | impl<'a> Thing<'a> {
| -- lifetime `'a` defined here
23 | pub fn get(&mut self) -> &'a mut Data {
| - let's call the lifetime of this reference `'1`
24 | self.data
| ^^^^^^^^^ method was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`
Copy
implementation of shared references? So copying a &'a Data gives a &'a Data. Simple enough.self.data
is. Is it an (implicit) re-borrow that "somehow" ties the anonymous lifetime of &mut self
to &'a mut Data
... but then realizes 'a
is not a subtype of the anonymous lifetime?pub struct Thing<'a> {
data: &'a Data,
}
impl<'a> Thing<'a> {
pub fn get(&self) -> &'a Data {
&*self.data
}
}
Any pointers what documentation or reference explains how Rust actually comes to the conclusion that Case 2 is bad would be highly appreciated as well, Thank You!
1 post - 1 participant
🏷️ Rust_feed