1

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
        }
    }
}

1 Answer 1

6

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(),
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.