🦀 Rust Master Class - Chapter 19: Type Coercion Speed dating.
Three minutes, a stranger, no expectations.
But we clicked. becomes — two different types, suddenly compatible.
The compiler sees it before you do.
Coercion in Rust refers to the implicit conversion of one type into another .
1.
Deref Coercion This is the most common form of coercion.
If a type implements the trait, a reference to () can be implicitly converted to a reference of its target type () ``.
Key Concept: A common example is converting to or to ``.
DerefMut: This allows for mutable coercion, such as converting to ``.
Code Example: `rust fn accept_str(s: &str) { // Output to console println!("Received: {s}"); } fn main() { // Create a new variable let s = String::from("Some String"); accept_str(&s); // &String is coerced to &str via Deref } `
2.
Reference Coercion Rust allows a mutable reference () to be coerced into an immutable reference () .
Code Example: `rust fn accepts_immut_ref(s: &String) { // Output to console println!("{s}"); } fn main() { // Create a mutable variable let mut s = String::from("Some String"); // Create a mutable variable let mut_ref = &mut s; accepts_immut_ref(mut_ref); // &mut String is coerced to &String } `
3.
Function Item Coercion Every function in Rust has its own unique "function item type" .
Code Example: `rust fn email_notification(user: &str) { /* ... */ } fn notify_user(method: fn(&str), s: &str) { method(s); } fn main() { // email_notification (item type) coerced to fn(&str) (pointer) notify_user(email_notification, "Alice"); } `
4.
Trait Object Coercion A reference to a concrete type can be coerced into a trait object , provided that implements the specified .
5.
Transitivity and Chaining Coercion is transitive: if type can be coerced to , and can be coerced to , then Rust can coerce directly to ``.
Code Example:
6.
Least Upper Bound Coercion In contexts with multiple branches, such as an expression or arms, Rust attempts to find a "least upper bound" type that all branches can coerce to ``.
Code Example:
7.
Subtyping and Variance While Rust does not have traditional class inheritance, it uses subtyping for lifetimes ``.
Covariance: A reference with a longer lifetime () is a subtype of a shorter one () and can be coerced into it ``.
Contravariance: This applies to function arguments; a function that handles any lifetime can be coerced to one that handles a specific, longer lifetime ``. 📖 Download the full PDF: https://drive.google.com/file/d/1ul-u10jUFwMkSMuica69QpEZ4Qpqup2E/view?usp=sharing Part 19 of the Rust Master Class series — STEM EdTech | Automation Consulting | Rust Tutoring RustLang #Programming #LearnToCode #STEM #EdTech