Tutorial by Examples

The . operator in Rust comes with a lot of magic! When you use ., the compiler will insert as many *s (dereferencing operations) necessary to find the method down the deref "tree". As this happens at compile time, there is no runtime cost of finding the method. let mut name: String = &quo...
Given two types T and U, &T will coerce (implicitly convert) to &U if and only if T implements Deref<Target=U> This allows us to do things like this: fn foo(a: &[i32]) { // code } fn bar(s: &str) { // code } let v = vec![1, 2, 3]; foo(&v); // &Vec&l...
For functions that need to take a collection of objects, slices are usually a good choice: fn work_on_bytes(slice: &[u8]) {} Because Vec<T> and arrays [T; N] implement Deref<Target=[T]>, they can be easily coerced to a slice: let vec = Vec::new(); work_on_bytes(&vec); le...
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...
Deref has a simple rule: if you have a type T and it implements Deref<Target=F>, then &T coerces to &F, compiler will repeat this as many times as needed to get F, for example: fn f(x: &str) -> &str { x } fn main() { // Compiler will coerce &&&&&&a...

Page 1 of 1