Answers for "rust•armanazi•generic•monomorphization"

0

rust•armanazi•generic•monomorphization

let integer = Some(5);
let float = Some(5.0);
When Rust compiles this code, it performs monomorphization. During that process, the compiler reads the values that have been used in Option<T> instances and identifies two kinds of Option<T>: one is i32 and the other is f64. As such, it expands the generic definition of Option<T> into Option_i32 and Option_f64, thereby replacing the generic definition with the specific ones.

The monomorphized version of the code looks like the following. The generic Option<T> is replaced with the specific definitions created by the compiler:

Filename: src/main.rs


enum Option_i32 {
    Some(i32),
    None,
}

enum Option_f64 {
    Some(f64),
    None,
}

fn main() {
    let integer = Option_i32::Some(5);
    let float = Option_f64::Some(5.0);
}
Because Rust compiles generic code into code that specifies the type in each instance, we pay no runtime cost for using generics. When the code runs, it performs just as it would if we had duplicated each definition by hand. The process of monomorphization makes Rust’s generics extremely efficient at runtime.
Posted by: Guest on March-18-2022

Code answers related to "rust•armanazi•generic•monomorphization"

Browse Popular Code Answers by Language