Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
707 views
in Technique[技术] by (71.8m points)

rust - How do I get an owned value out of a `Box`?

What is the implementation for this function:

fn unbox<T>(value: Box<T>) -> T {
    // ???
}

The only function in the documentation that looks like what I want is Box::into_raw. The following will type check:

fn unbox<T>(value: Box<T>) -> T {
    *value.into_raw()
}

This gives the error error[E0133]: dereference of raw pointer requires unsafe function or block. Wrapping it in an unsafe { ... } block fixes it.

fn unbox<T>(value: Box<T>) -> T {
    unsafe { *value.into_raw() }
}

Is this the correct implementation? If so, why is it unsafe? What does it mean?

Perhaps this question shows my general uncertainty of how Boxs actually work.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Dereference the value:

fn unbox<T>(value: Box<T>) -> T {
    *value
}

Way back in pre-1.0 Rust, heap-allocated values were very special types, and they used the sigil ~ (as in ~T). Along the road to Rust 1.0, most of this special-casing was removed... but not all of it.

This particular speciality goes by the name "deref move", and there's a proto-RFC about supporting it as a first-class concept. Until then, the answer is "because Box is special".

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...