如何初始化一个数组,以便Rust知道它是一个`String`数组而不是`str`?

3

我相对来说是 Rust 的新手,正在尝试做以下事情:

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
        }
    }
}

当我尝试构建这个时,会出现编译器错误:

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`

1
你的示例尝试将单个字符串与字符串数组进行比较。问题与 strString 无关。 - mcarton
1个回答

5
你应该回去重新阅读Rust编程语言,特别是关于字符串的章节String&str两种不同的类型
你可以用多种方法创建String,但我通常使用String :: from
let commands = [
    String::from("one thing"),
    String::from("another thing"),
    String::from("something else"),
];

然而,这种方法效率低下,因为每次都要分配内存。更好的方法是从&String转换为&str。此外,这并不能解决你的问题,因为你试图将单个值与集合进行比较。我们可以同时解决这两个问题:
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
    }
}

另请参阅:


1
非常有帮助,完全理解,并且编译完美。谢谢你的帮忙! - Cassandra O'Connell
1
@CassandraO'Connell,由于您可能想要根据命令进行调度,因此将命令名称映射到函数指针或整数ID的哈希映射可能更有用。否则,您仍需要将“command”与每个可能的值进行比较,使命令数组有些无用。 - Sven Marnach
对于一个更小、静态的项目,我可能会只使用match。创建HashMap会有分配开销,我们可以避免这种情况更长一段时间。@SvenMarnach - Shepmaster

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接