Search code examples
ruststructure

Is it possible to pass parameters into default values of a Rust structure?


I have a structure which I would like to be able to pass the ..Default::default() argument into when first initiating the structure. However, I would like the default implementation to be able to take in parameters so when I generate a vector I can use overridden defaults to generate it. Here is the code:

struct RandVec {
    vector: Vec<i64>,
    vec_len: i64,
    element_range: i64,
}

impl Default for RandVec {
    fn default() -> RandVec {
        RandVec {
            vec_len: 10000,
            element_range: 1000,
            /* The get_rand_vec() function takes in vector length and element range,
            I want to pass in vec_len and element_range so if I've declared them in
            in main() it takes those over the default values here */
            vector: get_rand_vec(/*vec_len*/, /*element range*/),
        }
    }
}

fn main() {
    let mut random_vector = RandVec {
        vec_len: 10,
        ..Default::default()
    };
}

Rust Playground, the get_rand_vec() function is included here.

I've looked through the documentation and I haven't found a way to do this, and I know that default() doesn't take in parameters, so I don't even know if it's possible to do with my approach. If there isn't a way to get default values to dynamically update what would be the recommended way to handle this?


Solution

  • Looks like you are looking into making a regular new function rather than using Default::default() here.

    The Struct { ..Default::default() } is nothing special in Rust, the syntax is actually Struct { ..any_expression } and the expression cannot know about the rest of the structure, therefore there is no way to pass parameters into default values using this syntax.