How to stop "thread 'main' panicked at" if no value is give a start

Hi,

let pattern = std::env::args().nth(1).expect("no City given. run weather cityname");

give me this output if no cityname is given to the binary at start...

./weather
thread 'main' panicked at src/main.rs:22:43:
no City given. run weather cityname
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Aborted

How make it right that I only the the Message: no City given. run weather cityname

thanks

Assuming this is just part of main, you can try something like

let Some(pattern) = std::env::args().nth(1) else {
    println!("no City given. run weather cityname");
    return;
};  

In this case, since its an error message, shouldn't it be

eprintln!("no City given. run weather cityname");
1 Like

Yes, indeed. And a non-zero exit code would also be nice. A better help message would also be nicer. Using clap could also be nicer.

I was just trying to keep things as simple as possible here though ^^

2 Likes

thanks....

how to convert args to string ?

let pattern = format!(args.to_string);

help: you might be missing a string literal to format with

because can not use the "args" as is.... need string for my
code that this works

I’m not sure what you mean by “convert args to string”. args is essentially a list of strings. If you want to combine it all into a single string… well… you should probably share your use-case for why you want to do that, but I suppose you could concatenate it all separated by spaces if you really want to? With std, you could collect into a Vec<String>, then use .join(" "). Or get itertools to do it in one step.

1 Like

How are you learning Rust? Have you tried reading the Rust book? It has translations in several languages if English is not your native language.

Please continue to ask questions if that is the best way for you to learn. I suggest using the Rust book to make sure you also have examples and written material to guide you.

1 Like

thanks for the hint

Args::parse() is interesting; where is that function from? I thought we were discussing std::env::Args, still, but that one doesn’t have any such API?

Edit: Ah, you’re using clap now!

yes try to use clap

did mod the Code a bit:

println!("{:?}", city);

./weather --city Objat
Platform: x86_64-unknown-linux-gnu Program was compiled on x86_64-unknown-linux-gnu
Args { city: "Objat", count: 1 }


But how to select only the City in this case: Objat ?

The city is in the .city field of your args struct now. E.g. try changing it to let city = args.city;.

many many thanks!

./weather --city Objat
Platform: x86_64-unknown-linux-gnu Program was compiled on x86_64-unknown-linux-gnu
"Objat"
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.