Rust
Auto-dereferencing
Sök…
Punktoperatören
Den . operatör i Rust kommer med mycket magi! När du använder . kommer kompilatorn att sätta in så många * s (dereferencing operationer) som är nödvändiga för att hitta metoden ner i "duf" -trädet. Eftersom detta händer vid sammanställningstillfället finns det inga runtime-kostnader för att hitta metoden.
let mut name: String = "hello world".to_string();
// no deref happens here because push is defined in String itself
name.push('!');
let name_ref: &String = &name;
// Auto deref happens here to get to the String. See below
let name_len = name_ref.len();
// You can think of this as syntactic sugar for the following line:
let name_len2 = (*name_ref).len();
// Because of how the deref rules work,
// you can have an arbitrary number of references.
// The . operator is clever enough to know what to do.
let name_len3 = (&&&&&&&&&&&&name).len();
assert_eq!(name_len3, name_len);
Auto dereferencing fungerar också för alla typer som implementerar std::ops::Deref drag.
let vec = vec![1, 2, 3];
let iterator = vec.iter();
Här är iter inte en metod för Vec<T> , utan en metod för [T] . Det fungerar eftersom Vec<T> implementerar Deref med Target=[T] vilket gör att Vec<T> förvandlas till [T] när du avbryts av operatören * (som kompilatorn kan infoga under a . ).
Döva tvång
Givet två typer T och U kommer &T att tvingas (implicit konvertera) till &U om och bara om T implementerar Deref<Target=U>
Detta gör att vi kan göra sådana saker:
fn foo(a: &[i32]) {
// code
}
fn bar(s: &str) {
// code
}
let v = vec![1, 2, 3];
foo(&v); // &Vec<i32> coerces into &[i32] because Vec<T> impls Deref<Target=[T]>
let s = "Hello world".to_string();
let rc = Rc::new(s);
// This works because Rc<T> impls Deref<Target=T> ∴ &Rc<String> coerces into
// &String which coerces into &str. This happens as much as needed at compile time.
bar(&rc);
Använda Deref och AsRef för funktionsargument
För funktioner som behöver ta en samling objekt är skivor vanligtvis ett bra val:
fn work_on_bytes(slice: &[u8]) {}
Eftersom Vec<T> och matriser [T; N] implementera Deref<Target=[T]> , de kan lätt tvingas till en skiva:
let vec = Vec::new();
work_on_bytes(&vec);
let arr = [0; 10];
work_on_bytes(&arr);
let slice = &[1,2,3];
work_on_bytes(slice); // Note lack of &, since it doesn't need coercing
Men istället för att uttryckligen kräva en skiva, kan funktionen göras för att acceptera alla typer som kan användas som en skiva:
fn work_on_bytes<T: AsRef<[u8]>>(input: T) {
let slice = input.as_ref();
}
I det här exemplet tar funktionen work_on_bytes valfri typ T som implementerar as_ref() , vilket returnerar en referens till [u8] .
work_on_bytes(vec);
work_on_bytes(arr);
work_on_bytes(slice);
work_on_bytes("strings work too!");
Deref implementering för Alternativ och omslagstruktur
use std::ops::Deref;
use std::fmt::Debug;
#[derive(Debug)]
struct RichOption<T>(Option<T>); // wrapper struct
impl<T> Deref for RichOption<T> {
type Target = Option<T>; // Our wrapper struct will coerce into Option
fn deref(&self) -> &Option<T> {
&self.0 // We just extract the inner element
}
}
impl<T: Debug> RichOption<T> {
fn print_inner(&self) {
println!("{:?}", self.0)
}
}
fn main() {
let x = RichOption(Some(1));
println!("{:?}",x.map(|x| x + 1)); // Now we can use Option's methods...
fn_that_takes_option(&x); // pass it to functions that take Option...
x.print_inner() // and use it's own methods to extend Option
}
fn fn_that_takes_option<T : std::fmt::Debug>(x: &Option<T>) {
println!("{:?}", x)
}
Enkelt Deref-exempel
Deref har en enkel regel: om du har en typ T och den implementerar Deref<Target=F> , då &T tvingas till &F , kommer kompilatorn att upprepa detta så många gånger som behövs för att få F, till exempel:
fn f(x: &str) -> &str { x }
fn main() {
// Compiler will coerce &&&&&&&str to &str and then pass it to our function
f(&&&&&&&"It's a string");
}
Deref-tvång är särskilt användbart när du arbetar med pekartyper, till exempel Box eller Arc , till exempel:
fn main() {
let val = Box::new(vec![1,2,3]);
// Now, thanks to Deref, we still
// can use our vector method as if there wasn't any Box
val.iter().fold(0, |acc, &x| acc + x ); // 6
// We pass our Box to the function that takes Vec,
// Box<Vec> coerces to Vec
f(&val)
}
fn f(x: &Vec<i32>) {
println!("{:?}", x) // [1,2,3]
}