gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:14:12 25 4
gpt4 key购买 nike

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

最佳答案

你应该回去重新阅读The Rust Programming Language ,特别是 chapter on strings . String&str两种不同的类型

您可以在 number of ways 中创建 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
}
}

另见:

关于rust - 我如何初始化一个数组,以便 Rust 知道它是一个 `String` s 而不是 `str` 的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48138841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com