Defining the child structures

We have two types of struct—parent and child. Here, the struct of Room is the parent and it has two children: the window definition and room size. They are very different beasts as the window definition is a Vec type, while the other is just a struct type.

For the room area, we can use the following when creating an instance of the room type:

room_area: Area {width: 2.3f32, length: 4.3f32} 

We are defining room_area, for which we will then define an inline variable which will act as the pointer to the area structure and, finally, create the size of the room. This is accessed using the following code snippet:

println!("The room width is {}m by {}m", room.room_area.width, room.room_area.length); 

Finally, we have to define the vector of Windows.

This is done in a very similar way to how we define any other vector, which is as follows:

window: vec![  
        Window { 
            window_area: Area {width: 1.3f32, length: 1.4f32}, 
            window_type: "Main".to_owned(), 
            has_blinds: true, 
            curtain_color: "Blue".to_owned(), 
            has_lock: false, 
            top_open: true, 
            single_window: true, 
        }, 
        Window { 
            window_area: Area {width: 0.9f32, length: 1.1f32}, 
            window_type: "Small".to_owned(), 
            has_blinds: true, 
            curtain_color: "Blue".to_owned(), 
            has_lock: false, 
            top_open: true, 
            single_window: true, 
        } 

We will then add a few more println! lines to show we have some data:

println!("The room width is {}m by {}m", room.room_area.width, room.room_area.length);  
let ref window_two = room.window[1]; 
println!("Window 2 is {}m by {}m and has {} curtains", window_two.window_area.width, window_two.window_area.length,  window_two.curtain_color); 

When compiled, the code produces the following result:

We have very quickly, and simply, created a multi-level structure.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset