Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize an array so that Rust knows it's an array of `String`s and not `str`?

Tags:

rust

I'm relatively new to Rust and am trying to do the following:

pub fn route(request: &[String]) {
    let commands = ["one thing", "another thing", "something else"];

    for command in commands.iter() {
        if command == request {
            // do something
        } else {
            // throw error
        }
    }
}

When I try to build this, I get a compiler error:

error[E0277]: the trait bound `&str: std::cmp::PartialEq<[std::string::String]>` is not satisfied
 --> src/main.rs:5:20
  |
5 |         if command == request {
  |                    ^^ can't compare `&str` with `[std::string::String]`
  |
  = help: the trait `std::cmp::PartialEq<[std::string::String]>` is not implemented for `&str`
  = note: required because of the requirements on the impl of `std::cmp::PartialEq<&[std::string::String]>` for `&&str`
like image 695
Cassandra O'Connell Avatar asked Dec 02 '25 20:12

Cassandra O'Connell


1 Answers

You should go back and re-read The Rust Programming Language, specifically the chapter on strings. String and &str are two different types.

You can create Strings in a number of ways, but I commonly use String::from:

let commands = [
    String::from("one thing"),
    String::from("another thing"),
    String::from("something else"),
];

However, this is inefficient as you are allocating memory each time. It's better to instead go the other way, from &String to &str. Additionally, this doesn't solve your problem because you are attempting to compare a single value to a collection. We can solve both at once:

let commands = ["one thing", "another thing", "something else"];

for command in commands.iter() {
    if request.iter().any(|r| r == command) {
        // do something
    } else {
        // throw error
    }
}

See also:

  • What are the differences between Rust's `String` and `str`?
  • How to create a String directly?
like image 106
Shepmaster Avatar answered Dec 05 '25 15:12

Shepmaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!