How to pass parameters to the struct from the file

I have two algorithms which solve some optimization problem. These algorithms are represented by two struct with some default parameters, the latter I easily able to change in my code when calling evaluation method, so there's no problem with it.

I want to make an app console when I could ask from user if he wants to change some parameters through some text-file.

So, the question is: how to make it more elegant way? I don't want to change all of the fields (some of them need to remain Default).

Perhaps I could using object of the struct from main.rs code:

 let mut alg = Algorithm {
        n: 4,
        m: 2,
        bounds: vec![vec![-5., 5.]; 2],
        CONST: 0.45777,
        prob: 0.2,
        epochs: 10,
        score_function: some_other_algo::CostFunctionType {
             cost_function: fn_pointer,
        },
        // groups: 3,
        // pop: todo!(),
        // minimize: true,
        ..Default::default()
    };

to make a new .txt file each time after end of the algorithm, with some template like

        // n: 4,
        // m: 2,
        // bounds: vec![vec![-5., 5.]; 2],
        // CONST: 0.45777,
        // prob: 0.2,
        // epochs: 10,
        // score_function: some_other_algo::CostFunctionType {
        //     cost_function: fn_pointer,
        // },
        // groups: 3,
        // pop: todo!(),
        // minimize: true,

Here I could probably use // pattern to see what params need to be handled. However, next problem is matching: in such a scenario I need to match every field separately (since there are no traversal over the struct fields in rust).
So, is it more elegant way? Can I use some crates for deserialization here?

If the problem you're trying to solve is just "let the user only specify overriding values, and fallback to default values for fields not listed" serde may be able to do what you want already with #[serde(default)]

1 Like

So, use it with serde and serde_json crates, firstly writing my json-file to some .txt file with default parameters using #[derive(Serialization, Deserialization)].
Then user changes some parameters in .txt file and, using deserialization, I'm put this into my algo.