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
902 views
in Technique[技术] by (71.8m points)

rust - Dereferencing Box<T> gives back value instead of reference

I can't seem to figure out why:

let a = Box::new(5i32);
let _:() = *a;

tells me that the assigned type on the second line is i32 and not &i32 since Deref.deref() (which I assume is being called at *a), returns &T.

Also, if I were to call deref() myself:

let _:() = <Box<i32> as Deref>::deref(&a);

I get the expected &i32.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Dereferencing doesn't necessarily produce an (intermediate) value. Consider

let b = Box::new(1);
(*b).clone();

The method i32::clone() is called with a &self argument where the reference points to the value inside the box, not to a temporary value that could be produced by (*b).

The trait Deref is part of implementing dereferencing (just like DerefMut).

There is no corresponding trait to what * can additionally do on a box: Move the inner value out and discard the box; this is colloquially called DerefMove but remains a compiler-hardcoded box speciality at this point.

When the compiler sees (*a), it has to infer whether to use Deref, DerefMut or “DerefMove”; it is inferred from how the expression is used: if you call a &self method on the result, Deref is used, for example.

Edited: Inherently copyable types (trait Copy), use Deref followed by copy instead of “DerefMove”; this is then no longer resticted to Box, but works with all smart pointers.


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

...