Reputation: 67
In the following code, how can I access the string "hello"
(which I passed when defining m
)?
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
impl Message {
fn call(&self) {
// How to access "hello" string from here?
}
}
let m = Message::Write(String::from("hello"));
m.call();
Upvotes: 2
Views: 636
Reputation: 18109
Since enum Message
can be in any number of states, you have to be in correct state to extract hello.
fn call(&self) {
match self {
Message::Write(string) => println!("{}", string),
_ => {},
}
}
EDIT: user4815162342 solution is also right, you can use match
or if let
interchangeably.
Upvotes: 2
Reputation: 155246
You need to use pattern matching to extract the string:
if let Message::Write(s) = self {
assert_eq!(s, "hello");
}
Upvotes: 3