1

Prologue: I'm at my first day on Rust here.

This is my demo code:

fn main() {
    println!("Hello, world!");
    println!(Move::X.to_string());
}

enum Move {
    Empty,
    X,
    O,
}

impl Move {
    fn to_string(&self) -> &'static str {
        match self {
            Move::Empty => "Empty",
            Move::X => "X",
            Move::O => "O"
        }
    }
}

This is not compiling because of these errors

enter image description here

I kindly ask you a fix, but mainly I need an explanation.

I tried println!(String::from(Move::X.to_string())); but the error is identical.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
realtebo
  • 23,922
  • 37
  • 112
  • 189
  • 1
    Does this answer your question? [println! error: expected a literal / format argument must be a string literal](https://stackoverflow.com/questions/27734708/println-error-expected-a-literal-format-argument-must-be-a-string-literal) – Chayim Friedman May 23 '22 at 17:51

2 Answers2

6

Because println! is a macro in where the first term expects a string literal. That string literal is evaluated in compile time (so it can never be a reference to actual data).

You can use the newly added formatting string:

let x = Move::X.to_string();
println!("{x}");

or the usual formatting as the error message suggest you to do:

println!("{}", Move::X.to_string())

Playground

Netwave
  • 40,134
  • 6
  • 50
  • 93
  • 1
    Might be worth mentioning that the content of the formatting string literal is evaluated at *compile time*, making it obvious that it can never be a reference to actual data. – Finomnis May 23 '22 at 14:24
1

First of all, Move::X.to_string(): String, not Move::X.to_string(): &str or Move::X.to_string(): str. See this for an explanation. So even if println! did accept a &str, it's not by building a String that you would solve that issue (even though when calling a function that requires a &str, Rust can Deref String to a &str — but println! is not a function).

Second, the println! macro always and only wants a string literal as its first "argument". That's because it must be able to know at compile time what is the formatting required.

jthulhu
  • 7,223
  • 2
  • 16
  • 33