我如何初始化一个数组,以便 Rust 知道它是一个 `String` 数组而不是 `str`? [英] How do I initialize an array so that Rust knows it's an array of `String`s and not `str`?

查看:32
本文介绍了我如何初始化一个数组,以便 Rust 知道它是一个 `String` 数组而不是 `str`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 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`

推荐答案

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

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

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

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"),
];

然而,这是低效的,因为您每次都在分配内存.最好是相反的方式,从 &String&str.此外,这并不能解决您的问题,因为您正在尝试将单个值与集合进行比较.我们可以同时解决两个问题:

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

另见:

这篇关于我如何初始化一个数组,以便 Rust 知道它是一个 `String` 数组而不是 `str`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆