Rust Posts

9 posts in this category

Skip some fields when serializing
Using serde, we can serialize a data structure into different formats, for example, JSON: ```rust #[derive(Serialize)]...
Rust
Notes about Vector memory allocation
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 ...
Rust
Blanket Implementation
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: ```r...
Rust
The Never Type
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: ```rust...
Rust
Lifetime Elision Rules
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: ```rust // 🚫 would n...
Rust
Dealing with Integer Overflow
Overflow can happen when doing integer arithmetics in Rust, for example: ```rust let _ = 255u8 + 1;...
Rust
Deref and DerefMut
The traits [`std::ops::Deref`](https://doc.rust-lang.org/std/ops/trait.Deref.html) and [`std::ops::DerefMut`](https://doc.rust-lang.org/std/ops/trait.DerefMut.html) are used for **explicit dereference...
Rust
Implement external traits for external types
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, bo...
Rust
GUI Druid Custom Widget
To create a custom widget in [Druid](https://linebender.org/druid/), we create a new struct and implement [Widget](https://docs.rs/druid/latest/druid/trait.Widget.html) trait. Or create a function tha...
Rust