Search
 
SCRIPT & CODE EXAMPLE
 

RUST

armanriazi•rust•generic•monomorphization


{
Dispatch is the mechanism to determine which specific version of code is actually run when it involves polymorphism. Two major forms of dispatch are static dispatch and dynamic dispatch. While Rust favors static dispatch, it also supports dynamic dispatch through a mechanism called ‘trait objects’.
}

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:

versions of a polymorphic function (or any polymorphic entity) during compilation is called Monomorphization.

let integer = Some(5);
let float = Some(5.0);



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.
This is opposed to dynamic dispatch
Comment

PREVIOUS NEXT
Code Example
Rust :: rust named tuple 
Rust :: lifetime may not live long enough 
Rust :: rust comments 
Rust :: armanriazi•rust•error•E0502•cannot borrow `s` as mutable because it is also borrowed as immutable 
Rust :: declare an array with signle value Rust 
Rust :: armanriazi•rust•error•E0277•`Point<{integer}, {float}` cannot be formatted using ` 
Rust :: armanriazi•rust•error•E0615•attempted to take value of method `collect` on type 
Rust :: armanriazi•rust•concept•memoization•lazy•evaluation 
Rust :: rust currying, preset some arguments 
Rust :: rust•armanriazi•slice•vs•char•vec 
Rust :: decimal in rust 
Rust :: rust•armanriazi•refactor 
Lua :: roblox studio teleport on touch 
Lua :: lua exponent 
Lua :: if part is touched 
Lua :: roblox loop players 
Lua :: roblox studio Teleport service not working 
Lua :: lua in pairs 
Lua :: lua while loops 
Lua :: lua type of 
Lua :: lua string to date 
Lua :: lua print table 
Lua :: while loop lua 
Lua :: roblox create part script 
Lua :: Roblox Studio Mouse Shaking 
Matlab :: matlab title with variable 
Matlab :: matlab 1d matrix declarationg 
Basic :: how to open d drive using conda prompt 
Basic :: JsonFileWrapper 
Elixir :: elixir enum all 
ADD CONTENT
Topic
Content
Source link
Name
4+2 =