1

I have an enum that looks like this:

enum Foo {
  Bar,
  Baz,
}

I want to make a method that returns a &str based on which variant is passed. Basically the Rust equivalent of the following Python code:

class Foo:
    def __str__(self):
        ...

My first guess at doing this would be something like:

impl Foo {
  fn to_str(self) -> &str {
    match self {
      Self::Bar => "Example str",
      Self::Baz => "Another example str",
    }
  }
}

But I think there must be a better way to do this... Maybe using traits or something like that? I have never used those before and I would be lying if said that I understand them. The most important requirement is that it automatically works with println!() like this (if that is even possible):

println!("Current state: {}", Foo::Bar);
gwaadie
  • 15
  • 5
  • 2
    You want to implement the [`Display`](https://doc.rust-lang.org/std/fmt/trait.Display.html) trait for that. – Finomnis Apr 22 '23 at 21:50
  • 1
    ... or `#[derive(Debug)]`. Then you can return `String` (not `&str`) with `format!("{:#?}",self)`. – mhvelplund Apr 23 '23 at 09:07

0 Answers0