gpt4 book ai didi

arrays - 如何编写内部数组长度不同的嵌套数组?

转载 作者:行者123 更新时间:2023-12-03 11:26:00 25 4
gpt4 key购买 nike

我有一个生成字谜的函数,我想测试它,所以我有以下内容:

pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> {
unimplemented!()
}

fn main() {
let words = [
"eat".to_string(),
"tea".to_string(),
"tan".to_string(),
"ate".to_string(),
"nat".to_string(),
"bat".to_string(),
]
.to_vec();
let answer = [["ate", "eat", "tea"], ["nat", "tan"], ["bat"]];
let solution = group_anagrams(words);
assert_eq!(answer, solution);
}

我不知道如何以编译的方式编写它:

error[E0308]: mismatched types
--> src/main.rs:15:42
|
15 | let answer = [["ate", "eat", "tea"], ["nat", "tan"], ["bat"]];
| ^^^^^^^^^^^^^^ expected an array with a fixed size of 3 elements, found one with 2 elements
|
= note: expected type `[&str; 3]`
found array `[&str; 2]`

( Playground )

最佳答案

group_anagrams返回 Vec<Vec<String>> .一种解决方法是制作 answer嵌套 Vec s 而不是嵌套数组来匹配。

let answer = vec![
vec!["ate", "eat", "tea"],
vec!["nat", "tan"],
vec!["bat"],
];

如果你不想嵌套Vec因此,您可以尝试改用切片,因为切片还会将编译时长度从类型中移出并移到运行时存储中。

let answer = [
&["ate", "eat", "tea"][..],
&["nat", "tan"][..],
&["bat"][..],
];

当然,这看起来更丑了。而且它仍然无法编译程序的其余部分。 (我将把它留给读者作为练习。)


原始代码无法编译,因为内部数组的长度不同,因此类型也不同:[&str; 3] , [&str; 2] , 和 [&str; 1] , 分别。这是三种不同的类型,数组不能包含异构项。

如果内部数组恰好具有相同的长度,则原始代码可以编译。如果每个数组都有三个单词,那么整体类型将为 [[&str; 3]; 3] :

let answer: [[&str; 3]; 3] = [
["ate", "eat", "tea"],
["nat", "tan", "x"],
["bat", "y", "z"],
];

关于arrays - 如何编写内部数组长度不同的嵌套数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61086320/

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