Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

println! error: expected a literal / format argument must be a string literal

Tags:

rust

This extremely simple Rust program:

fn main() {     let c = "hello";     println!(c); } 

throws the following compile-time error:

error: expected a literal  --> src/main.rs:3:14   | 3 |     println!(c);   |              ^ 

In previous versions of Rust, the error said:

error: format argument must be a string literal.      println!(c);               ^ 

Replacing the program with:

fn main() {     println!("Hello");     } 

Works fine.

The meaning of this error isn't clear to me and a Google search hasn't really shed light on it. Why does passing c to the println! macro cause a compile time error? This seems like quite unusual behaviour.

like image 301
Mike Vella Avatar asked Jan 01 '15 21:01

Mike Vella


1 Answers

This should work:

fn main() {     let c = "hello";     println!("{}", c); } 

The string "{}" is a template where {} will be replaced by the next argument passed to println!.

like image 195
evotopid Avatar answered Oct 14 '22 08:10

evotopid