这个函数的实现是什么:
fn unbox<T>(value: Box<T>) -> T {
// ???
}
Run Code Online (Sandbox Code Playgroud)
文档中唯一看起来像我想要的功能Box::into_raw.以下将进行类型检查:
fn unbox<T>(value: Box<T>) -> T {
*value.into_raw()
}
Run Code Online (Sandbox Code Playgroud)
这给出了错误error[E0133]: dereference of raw pointer requires unsafe function or block.将其包装在一个unsafe { ... }块中可以修复它.
fn unbox<T>(value: Box<T>) -> T {
unsafe { *value.into_raw() }
}
Run Code Online (Sandbox Code Playgroud)
这是正确的实施吗?如果是这样,为什么它不安全?这是什么意思?
也许这个问题显示了我对如何Box实际工作的一般不确定性.
以下是Rust编程语言中的Deref示例,除了我添加了另一个断言.
为什么assert_eq和deref平等'a'?为什么我需要*手动调用一次deref?
use std::ops::Deref;
struct DerefExample<T> {
value: T,
}
impl<T> Deref for DerefExample<T> {
type Target = T;
fn deref(&self) -> &T {
&self.value
}
}
fn main() {
let x = DerefExample { value: 'a' };
assert_eq!('a', *x.deref()); // this is true
// assert_eq!('a', x.deref()); // this is a compile error
assert_eq!('a', *x); // this is also true
println!("ok");
}
Run Code Online (Sandbox Code Playgroud)
如果我取消注释该行,我会收到此错误:
error[E0308]: mismatched …Run Code Online (Sandbox Code Playgroud) 从Rust库中读取文档时遇到了这段代码:
for (ent, pos, vel) in (&*entities, &mut pos_storage, &vel_storage).join() {
println!("Processing entity: {:?}", ent);
*pos += *vel;
}
Run Code Online (Sandbox Code Playgroud)
原始链接:https : //slide-rs.github.io/specs/08_join.html
&*实体在这里做什么。据我所知,它是在取消引用实体,然后再次引用它?
如果我的取消引用链中有任何不可变的引用,我似乎无法改变任何东西。一个样品:
fn main() {
let mut x = 42;
let y: &mut i32 = &mut x; // first layer
let z: &&mut i32 = &y; // second layer
**z = 100; // Attempt to change `x`, gives compiler error.
println!("Value is: {}", z);
}
Run Code Online (Sandbox Code Playgroud)
我收到编译器错误:
fn main() {
let mut x = 42;
let y: &mut i32 = &mut x; // first layer
let z: &&mut i32 = &y; // second layer
**z = 100; // Attempt to …Run Code Online (Sandbox Code Playgroud)