enums give you a way of saying a value is one of a possible set of values.
We can create instances of each of the two variants of IpAddrKind like this:
enum IpAddrKind {
V4,
V6,
}
let four = IpAddrKind::V4;
let six = IpAddrKind::V6;
the variants of the enum are namespaced under its identifier
we can put data directly into each enum variant. This new definition of the IpAddr enum says that both V4 and V6 variants will have associated String values:
enum IpAddr {
V4(String),
V6(String),
}
let home = IpAddr::V4(String::from("127.0.0.1"));
let loopback = IpAddr::V6(String::from("::1"));
IpAddr::V4() is a function call that takes a String argument and returns an instance of the IpAddr type.
each variant can have different types and amounts of associated data. you can put any kind of data inside an enum variant: strings, numeric types, or structs, for example. You can even include another enum!
we’re also able to define methods on enums. Here’s a method named call that we could define on our Message enum:
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
impl Message {
fn call(&self) {
// method body would be defined here
}
}
let m = Message::Write(String::from("hello"));
m.call();