ANimator120
ANimator120

Reputation: 3401

Nested Default Struct Values in Rust

I'm trying to reference the default value of a structure while defining the default value of some other structure, nesting the default A inside the default B as it were. What is the correct way to do this in Rust?

use std::default::Default;

struct A {
    val_1: i32,
    val_2: i32,
    val_3: Vec<String>,
}

impl Default for A {
    fn default() -> A {
        A {
            val_1: 0,
            val_2: 0,
            val_3: vec!["Hello".to_string()],
        }
    }
}

struct B {
    val_1: i32,
    val_2: i32,
    val_3: A,
}

impl Default for B {
    fn default() -> B {
        B {
            val_1: 0,
            val_2: 0,
            val_3: _____ //<---- put the default value for struct A here
        }
    }
}

Upvotes: 1

Views: 702

Answers (1)

vallentin
vallentin

Reputation: 26157

You'd just call default() as you would with any other function, i.e. A::default() or Default::default().

impl Default for B {
    fn default() -> B {
        B {
            val_1: 0,
            val_2: 0,
            val_3: A::default(),
            // or
            // val_3: Default::default(),
        }
    }
}

Upvotes: 6

Related Questions