Rust: Difference between revisions
Jump to navigation
Jump to search
| Line 2: | Line 2: | ||
Swapping between different ownership/reference types in Rust is a pain. The generics can ripple throughout a program making maintenance/refactoring a big hassle. |
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 for a Genetic programming experiment: |
Consider some context that has a random number generator. I was wanting something similar for a Genetic programming experiment: |
||
pub struct Context { |
pub struct Context { |
||
Revision as of 03:26, 10 December 2016
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.
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 {
}