Search code examples
functionrustinitializationtraits

When implementing the default trait for a struct, and intializing its members using functions, are those functions evaluated once or several times?


I m having the following pseudocode inside a crate

pub static struct connection {
  pub Id: i32,
  pub speed: i32,
}

impl Default for connection {
  fn default() -> Self {
      connection {
          Id: open_connection(),
          Speed: get_speed_at_init(),
      }
  }
}

That crate is imported into an other project and run into several worker threads where each threads use the imported crate in an infinite loop.

Now will I be able to use self.connection.Id to perform network operations on it, or will open_connection() be evaluated several times resulting in opening too many connections instead of the expected just one time?


Solution

  • Several times. This can be trivially demonstrated:

    struct Struct;
    
    impl Default for Struct {
        fn default() -> Self {
            println!("default called");
            Struct
        }
    }
    
    fn main() {
        let s1 = Struct::default(); // prints "default called"
        let s2 = Struct::default(); // prints "default called"
    }
    

    playground

    There's nothing special about the Default trait or the default function. They work like any other trait and any other function.