I'm confused about this statement from the Rust Book:
There’s another advantage to using an enum rather than a struct: each variant can have different types and amounts of associated data. Version four type IP addresses will always have four numeric components that will have values between 0 and 255. If we wanted to store V4 addresses as four
u8values but still express V6 addresses as oneStringvalue, we wouldn’t be able to with a struct. Enums handle this case with ease:#![allow(unused_variables)] fn main() { enum IpAddr { V4(u8, u8, u8, u8), V6(String), } let home = IpAddr::V4(127, 0, 0, 1); let loopback = IpAddr::V6(String::from("::1")); }
But when I tried it with structs to store V4 addresses as four u8 values but still express V6 addresses as one String value its also doing the same without any errors.
#[derive(Debug)]
struct IpAddr {
V4:(u8, u8, u8, u8),
V6:String,
}
fn main () {
let home = IpAddr {
V4: (127, 1, 1, 1),
V6: String::from("Hello"),
};
println!("{:#?}", home);
}