Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

rust - Is there a more concise way to format .expect() message?

I currently have to use this to format a .expect() message:

fn main() {
    let x: Option<&str> = None;
    x.expect(&format!("the world is ending: {}", "foo")[..]);
}

Is there a less verbose way?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

I would do:

option.unwrap_or_else(|_| panic!("ah: {}", "nuts"))

Formatting a string is somewhat costly. This will avoid formatting the string unless it is really needed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...