struct MyCell<T> {
value: T
}
impl<T> MyCell<T> {
fn new(value: T) -> Self {
MyCell { value }
}
fn get(&self) -> &T {
&self.value
}
fn set(&self, new_value: T) {
unsafe {
*(&self.value as *const T as *mut T) = new_value;
}
}
}
fn set_to_local(cell: &MyCell<&i32>) {
let local = 100;
cell.set(&local);
}
fn main() {
let cell = MyCell::new(&10);
set_to_local(&cell);
}
调用时cell.set(&local)
,假设cell
is'x
和'&local
is 'y
,我被告知协方差规则将改变cell
from &MyCell<'x, &i32>
to的类型&MyCell<'y, &i32>
。
unsafe 块内的赋值如何影响参数的生命周期推断set()
?原始指针没有生命周期,那么编译器如何知道它应该使用协方差生成cell
并new_value
具有相同的生命周期?