Is there a way to compare a String with a &str?

Is there a way to compare a variable of type String with a variable of type &str. I know I can convert the latter to String but I don't want to do that. The code goes as follows:

mod print;
use std::env;

use commons::{error, help};
fn match_arg(args: &[String]) {
  let util = &args[0];

  match *util {
    "print" => print::main(args),
  }
}

fn main() {
  let args: Vec<String> = env::args().collect();

  // Skip the name of the program
  let args = &args[1..args.len()];

  match_arg(args);
}

If I try to convert the value in the match arm to a String, it will tell me that we cannot execute function calls inside a match arm. So I can do it with an if but I wondering if it's possible without converting it to an &str. Also I didn't said that but I'm just starting out with Rust so maybe there is another way to do what I try to do?

You can match util.as_str() { /* ... */ }.

You might want to guard against having no arguments, too.

fn match_arg(args: &[String]) {
    if let Some(util) = args.get(0) {
        match util.as_ref() {
            "print" => todo!(),
            _ => todo!(),
        }
    } else {
        // No arguments
        todo!();
    }
}
1 Like

Thanks a lot! I will of course handle the case I have no arguments but that was some pseudocode-like code to just demonstrate the problem. Have an amazing day and thanks for the help!

1 Like

You can also compare &str and String using the == operator because there is a `PartialEq<&str>` impl for `String.

if args.is_empty() {
  todo!("Handle empty args");
} else if args[0] == "print" {
  todo!("print");
} else {
  todo!("Print out usage");
}

Obviously a big chain of if-else statements is going to be a pain if you want to compare against more than one or two strings.

1 Like

Thanks a lot! Have a nice day :slight_smile:

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.