pointers - Understanding deref -
the following rust deref example http://doc.rust-lang.org/book/deref-coercions.html, except i've added assert.
my question why assert_eq deref equal 'a'? flip side question is: why need *
once i've manually called deref
?
use std::ops::deref; struct derefexample<t> { value: t, } impl<t> deref derefexample<t> { type target = t; fn deref(&self) -> &t { &self.value } } fn main() { let x = derefexample { value: 'a' }; assert_eq!('a', *x.deref()); // true // assert_eq!('a', x.deref()); // compile error assert_eq!('a', *x); // true println!("ok"); }
first, let's spell out generic types specific example: 'a'
char
, have (not valid syntax):
struct derefexample<char> { value: char, } impl<char> deref derefexample<char> { type target = char; fn deref(&self) -> &char { &self.value } }
notably, return type of deref
reference char
. shouldn't surprising that, when use x.deref()
, result &char
rather char
(which compiler tell if uncomment assertion). remember, @ point deref
normal method — it's implicitly invoked part of language-provided special syntax. *x
, example, call deref
, dereference result, when applicable. x.char_method()
, fn_taking_char(&x)
call deref
number of times , further result.
why deref
returns reference begin with, ask? isn't circular? well, no, isn't circular: reduces library-defined smart pointers built-in type &t
, compiler knows how dereference. , returning reference instead of value, avoid copy/move (which may not possible!) , allow &*x
(or &x
when it's coerced) refer actual char
derefexample
holds rather temporary copy.
Comments
Post a Comment