Using serde, we can serialize a data structure into different formats, for example, JSON: Output: Sometimes, we need to exclude some fields from the original data structure when serializing. To do so…
A Vector in Rust is fundamentally a (pointer, capacity, length) triplet. For example, a Vec<Char> containing two elements 'a' and 'b', with the capacity of 4, can be visualized as the following…
By using generic parameters, you can impl a trait for any type that satisfies some trait bounds, for example, implement trait ToString for every type T that implemented the Display trait: This…
Rust has a special type ! to imply that there is no return value. Usually called never type. It allows us to write code like this: We expect the num variable to have the type f32 if the input is…
Before Rust 1.0, writing code that returns a reference without any lifetime annotation wouldn’t compile. Because Rust does not know what’s the lifetime of the returned reference: In later versions…
Overflow can happen when doing integer arithmetics in Rust, for example: Rust handle overflow differently between Debug and Release mode: In debug mode, Rust includes checks for integer overflow that…
The traits std::ops::Deref and std::ops::DerefMut are used for explicit dereference operations (immutable or mutable), like: If a type T implements Deref<Target=U> or DerefMut<Target=U> like this: Any…
One of the rules for working with traits in Rust is: You are not allowed to implement a trait on a type if either the trait or the type is not local to your crate. For example, within your program…
To create a custom widget in Druid, we create a new struct and implement Widget trait. Or create a function that returns an impl Widget. Widget trait defined a few lifecycle methods for a Druid’s…