0

I have an enum MyEnum with as_str method implemented. What I want to do is to make it so that I could return &str formatted with SPACING from match arm.

For example instead of "ONE" I would get format!("{SPACING}ONE{SPACING}"), but the problem is format macro returns owned string and the attempt to return a reference results in cannot return reference to temporary value error.

enum MyEnum {
    One,
    Two,
    Three,
}

const SPACING: &'static str = " ";

impl MyEnum {
    fn as_str(&self) -> &str {
        match self {
            MyEnum::One => "ONE",
            MyEnum::Two => "TWO",
            MyEnum::Three => "THREE",
        }
    }
}

So I have two questions:

  1. Is there a way to format string literal and return a string slice?
  2. Also I'm a bit confused about what owns string literal inside match arms, I guess it's static and exists throughout the entire program execution time or is it wrong?
Slava.In
  • 597
  • 1
  • 9
  • 22

1 Answers1

1
  1. You cannot do that. As you explained yourself formatted String is a local variable and returning reference to it would result in a dangling reference, which rust strictly forbids. You must returned owned String instead. Consider implementing Display which will automatically provide implementation of ToString.

  2. You are correct. Every string literal in rust is a &'static str.

Aleksander Krauze
  • 3,115
  • 7
  • 18