Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
820 views
in Technique[技术] by (71.8m points)

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

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...