ImRajdeepB
ImRajdeepB

Reputation: 67

How to access argument of tuple enum inside method in Rust

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

Answers (2)

Daniel Fath
Daniel Fath

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),
      _ => {},
   }
}

Rust playground link

EDIT: user4815162342 solution is also right, you can use match or if let interchangeably.

Upvotes: 2

user4815162342
user4815162342

Reputation: 155246

You need to use pattern matching to extract the string:

if let Message::Write(s) = self {
    assert_eq!(s, "hello");
}

Playground

Upvotes: 3

Related Questions