Aloha.zone.io

Aloha's technical notes.

View on GitHub

Too Many Linked Lists

The Learn Rust With Entirely Too Many Linked Lists

Keynotes


Use trait in Rust for overloaded constructors:

// --- Not available
// fn foo(x: i32) {}
// fn foo(x: f32) {}
// ---

enum MyParams {
    Int(i32),
    Float(f32),
    MultiParams(i64, f64),
}

trait MyParamsTrait {
    fn to_params(&self) -> MyParams;
}

impl MyParamsTrait for i32 {
    fn to_params(&self) -> MyParams {
        MyParams::Int(*self)
    }
}

impl MyParamsTrait for f32 {
    fn to_params(&self) -> MyParams {
        MyParams::Float(*self)
    }
}

impl MyParamsTrait for (i64, f64) {
    fn to_params(&self) -> MyParams {
        MyParams::MultiParams(*self)
    }
}


// method definition
fn bar(x: &dyn MyParamsTrait) {}



Reference

Learn Rust With Entirely Too Many Linked Lists

Github repo for the linked lists