I'm currently learning Rust's lifetime and ownership. I encountered codes like this(minimized):
fn main() {
let mut text = Text::new();
println!("text: {:?}", text);
let mut byte = [1_u8];
let txt = text.get_text(byte);
println!("byte: {:?}", byte);
println!("txt: {:?}", txt);
byte[0] = 7_u8;
println!("byte: {:?}", byte);
println!("txt: {:?}", txt);
}
#[derive(Debug)]
struct Text<'a> {
temp: [u8; 1],
data: &'a [u8],
}
impl<'a> Text<'a> {
fn new() -> Self {
Text {
temp: [0_u8],
data: &[0],
}
}
fn get_lifetime(&self) -> &'a Self {
unsafe {
// &*(self as *const Self)
std::mem::transmute(self)
}
}
fn get_text(&mut self, byte: [u8; 1]) -> Text<'a> {
self.temp = byte;
let res = Text {
temp: [0_u8],
data: &self.get_lifetime().temp,
};
res
}
}
the output is
text: Text { temp: [0], data: [0] }
byte: [1]
txt: Text { temp: [0], data: [1] }
byte: [7]
txt: Text { temp: [0], data: [1] }
It seems that the slice data
inside variable text
point to some place independent of byte
. I think maybe the byte
is copied into get_text
. But is slice data
always refer to the copied one? How does Rust determine when to drop the copied byte?
Further more, I'm confused by the use of get_lifetime
. Can anyone further explain the usage, and whether it is safe to use?