Initialize a struct with one of the field in struct as empty /null/Nothing

All,

Need help in how to initialize a struct with one of the field in struct as empty /null.

Below is my code

fn main() {
}

struct Node {
x : i32,
link : Box<Node>,
}

struct Stack {
count :i32,
top : Box<Node>,
}

impl Stack {
pub fn creatstack() -> Self {
Self {
count : 0,
top : 'what should be written here to have empty/null/nothing' ,
}
}
}

Appreciate your help.

Just use an Option:

struct Stack {
    count :i32,
    top : Option<Box<...>>,
}

and set it to None:

pub fn creatstack() -> Self {
    Self {
        count: 0,
        top: None,
    }
}

BTW, Box is generic, you should provide the type of the content, e.g., Box<(int32, int32)>.

3 Likes

Appreciated for quick help, will try this option and yes Box in my code is of Box<Node>

Please use triple backquotes on separate lines. See:

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.