#Command parsing

21 messages · Page 1 of 1 (latest)

stoic coral
#

What is the best way to do a comparison of a string vector in Rust?

#

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...")
lapis hemlock
#

Are you looking for clap?
It is a command line argument parser but I'm pretty sure you can use it with normal string.

north forge
#

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"),
}
rapid shadowBOT
#
     Running `target/debug/playground`

1, 2, 3, 4
()
north forge
#

the input to the match has to be an &[&str] for this to work

stoic coral
#

but what if its type String instead of a str

north forge
#

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"

stoic coral
#

do they not need to be static strings?

#

?eval

let input = vec!["hello"];

match input {
    ["hello", not_matched] => println!("{:?}", not_matched),
    _ => println!("non matching")
}
rapid shadowBOT
#
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`.
stoic coral
#

ah

#

?eval

let input = vec!["hello"];

match input.as_slice() {
    ["hello", not_matched] => println!("{:?}", not_matched),
    _ => println!("non matching")
}
rapid shadowBOT
#
     Running `target/debug/playground`

non matching
()
stoic coral
#

?eval

let input = vec!["hello", "123"];

match input.as_slice() {
    ["hello", not_matched] => println!("{:?}", not_matched),
    _ => println!("non matching")
}
rapid shadowBOT
#
     Running `target/debug/playground`

"123"
()