Rust

From Hegemon Wiki
Jump to navigation Jump to search

Trait Objects

Swapping between different ownership/reference types in Rust is a pain. The generics can ripple throughout a program making maintenance/refactoring a big hassle.

Consider some context that has a random number generator. I was wanting something similar for a Genetic programming experiment:

pub struct Context {
   rng: StdRng,
}
impl Context {
   pub fn new() => Context {
       let seed: &[_] = &[1, 2, 3, 4];
       let mut rng = StdRng::from_seed(seed);
   }
}

This suffers from fixing the Rng to a specific implementation and prevents dependency inversion causing problems with things like testing.

Using Box's

Using boxes allows for generics to be avoided.

When adding a Box to the struct, it must be specified on the constructor, any mutator functions and the at the constructor call site. Users/consumers of the struct however are unaffected.

pub struct Context {
   rng: Box<Rng>,
}
impl Context {
   pub fn new(rng: Box<Rng>) -> Context {
       Context {rng: rng}
   }
}
fn do_something(ctx: &Context) {
    //...
}
fn main() {
   let seed: &[_] = &[1, 2, 3, 4];
   let mut rng = StdRng::from_seed(seed);
   let mut ctx = Context::new(Box::new(rng));
}


Using &'s

Requires lifetime to be specified in generics.

Useing trait's instead of the struct

pub struct ContextRaw {
}