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

Cas*_*ell 3 rust

我对 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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

She*_*ter 5

你应该回去重新阅读Rust 编程语言,特别是关于字符串的章节String&str两种不同的类型

您可以通过多种方式创建Strings ,但我通常使用:String::from

let commands = [
    String::from("one thing"),
    String::from("another thing"),
    String::from("something else"),
];
Run Code Online (Sandbox Code Playgroud)

然而,这是低效的,因为你每次都分配内存。最好走另一条路,从&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
    }
}
Run Code Online (Sandbox Code Playgroud)

也可以看看: