#Command parsing
21 messages · Page 1 of 1 (latest)
so i am writing a text client with a text input field that gets parsed as commands
with optional arguments and such
like for example: the pythonic way
match cmd:
case ["connect", ip]:
print(f"connect to {ip}")
case ["exit"]:
print("exiting...")
Are you looking for clap?
It is a command line argument parser but I'm pretty sure you can use it with normal string.
you can write a match like that with the right input type
?eval
let input: Vec<&str> = vec!["connect", "1, 2, 3, 4"];
match input.as_slice() {
["connect", ip] => println!("{ip}"),
["exit"] => return,
_ => println!("unknown"),
}
Running `target/debug/playground`
1, 2, 3, 4
()
the input to the match has to be an &[&str] for this to work
but what if its type String instead of a str
in that case you will unfortunately have to allocate a vector of references to the strings to make the convenient match syntax work
however you may want to use an argument parser like @lapis hemlock suggested, instead of just exact matching
it's not necessarily a great fit for the purpose but any parser has the advantage of giving the user more specific error messages than "nothing matched"
do they not need to be static strings?
?eval
let input = vec!["hello"];
match input {
["hello", not_matched] => println!("{:?}", not_matched),
_ => println!("non matching")
}
error[E0529]: expected an array or slice, found `Vec<&str>`
--> src/main.rs:5:5
|
4 | match input {
| ----- help: consider slicing here: `input[..]`
5 | ["hello", not_matched] => println!("{:?}", not_matched),
| ^^^^^^^^^^^^^^^^^^^^^^ pattern cannot match with input type `Vec<&str>`
For more information about this error, try `rustc --explain E0529`.
ah
?eval
let input = vec!["hello"];
match input.as_slice() {
["hello", not_matched] => println!("{:?}", not_matched),
_ => println!("non matching")
}
Running `target/debug/playground`
non matching
()
?eval
let input = vec!["hello", "123"];
match input.as_slice() {
["hello", not_matched] => println!("{:?}", not_matched),
_ => println!("non matching")
}
Running `target/debug/playground`
"123"
()