'How to add new argument in rust struct via the method?

in the following example I need to conditionally create other argument called number_3 without adding it to the struct. I wan to add this just like using setattr(self,'number_3',number) in python?

  • The reason I need this because I don't want the create new object of my class like MyClass { number: i32, number_2: i32, number_3:Some(None)} this number_3:Some(None) is Unnecessary to add. Also, most times I will never need it it is just for some edge cases.
  • Also, is it possible to initialize it with value None.
pub struct MyClass {
    number: i32,
    number_2: i32,
}

impl MyClass {
    pub fn my_function(mut self) -> i32 {
        self.number_3 = my_special_function().unwrap();
        if self.number_3 != Some(Nome) {
            return self.number * self.number_2 / self.number_3;
        } else {
            return self.number * self.number_2;
        };
    };


Solution 1:[1]

You cannot.

Besides explicitly initializing the field with None, you have few options:

Providing a constructor that does that (or two, for both cases):

impl MyClass {
    pub fn new(number: i32, number_2: i32) -> Self {
        Self { number, number_2, number_3: None }
    }
    pub fn with_three_numbers(number: i32, number_2: i32, number_3: i32) -> Self {
        Self { number, number_2, number_3: Some(number_3) }
    }

Implementing Default (usually by deriving it) then using the struct update syntax to add the default. This may mean even more boilerplate in your case, but may be worthwhile in case you have many optional fields:

#[derive(Default)]
pub struct MyClass { ... }

MyClass { number: 0, number_2: 1, ..MyClass::default() };

There were, and are, few RFCs and discussions around this subject, so you may be able to have defaulted fields in the future:

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1