gpt4 book ai didi

iterator - 我如何在 rust 中使用 Iterator 的 #map 和 #fold?

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

rustc 0.13.0-nightly (f168c12c5 2014-10-25 20:57:10 +0000)

我有以下代码。

fn main() {
let nums = vec![1i,2,3];

let strings = nums.iter()
.map(|n| n.to_string())
.fold(String::new, |a, b| a.push_str(b.as_slice()));

assert_eq!("123", strings.as_slice());
}

它应该将 nums 中的整数转换为它们的字符串表示形式,并将它们连接成一个大字符串。

这是我从 rustc 得到的:

test2.rs:6:31: 6:53 error: type `fn() -> collections::string::String` does not implement any method in scope named `push_str`
test2.rs:6 .fold(String::new, |a, b| a.push_str(b.as_slice()));
^~~~~~~~~~~~~~~~~~~~~~
test2.rs:8:29: 8:39 error: type `fn() -> collections::string::String` does not implement any method in scope named `as_slice`
test2.rs:8 assert_eq!("123", strings.as_slice());
^~~~~~~~~~
<std macros>:6:23: 6:33 error: the type of this value must be known in this context
<std macros>:6 if !((*given_val == *expected_val) &&
^~~~~~~~~~
<std macros>:1:1: 14:2 note: in expansion of assert_eq!
test2.rs:8:3: 8:41 note: expansion site
<std macros>:6:23: 6:33 error: the type of this value must be known in this context
<std macros>:6 if !((*given_val == *expected_val) &&
^~~~~~~~~~
<std macros>:1:1: 14:2 note: in expansion of assert_eq!
test2.rs:8:3: 8:41 note: expansion site
<std macros>:6:37: 6:50 error: the type of this value must be known in this context
<std macros>:6 if !((*given_val == *expected_val) &&
^~~~~~~~~~~~~
<std macros>:1:1: 14:2 note: in expansion of assert_eq!
test2.rs:8:3: 8:41 note: expansion site
<std macros>:7:23: 7:36 error: the type of this value must be known in this context
<std macros>:7 (*expected_val == *given_val)) {
^~~~~~~~~~~~~
<std macros>:1:1: 14:2 note: in expansion of assert_eq!
test2.rs:8:3: 8:41 note: expansion site
error: aborting due to 6 previous errors

所以它提示 fn() -> collections::string::String 类型,但我期望映射的结果只是一个普通的 collections::string::字符串

我在这里做错了什么,还是不应该像我在示例中尝试的那样使用 map ?

编辑:

哈哈 好的我发现了错误,String::new 是一个 fn() -> collections::string::String,所以这是一个错字!

正确的是 .fold(String::new(), |a, b| a.push_string(b.as_slice()));

最佳答案

有3个问题:

  1. String::new 缺少一个 (),应该是 String::new()
  2. 您必须从折叠闭包返回一个新状态,push_str 返回 ()
  3. 您必须使状态可变,以便您可以在其上使用 push_str

fn main() {
let nums = vec![1i,2,3];

let strings = nums.iter()
.map(|n| n.to_string())
.fold(String::new(), |mut a, b| {
a.push_str(b.as_slice());
a
});

assert_eq!("123", strings.as_slice());
}

关于iterator - 我如何在 rust 中使用 Iterator 的 #map 和 #fold?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26595418/

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