gpt4 book ai didi

使用rust 示例 : closure iterator any gives E0308

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

我一直在尝试 Rust by Example 书的代码,但在 https://doc.rust-lang.org/stable/rust-by-example/fn/closures/closure_examples/iter_any.html 上难住了。

error[E0308]: mismatched types
--> Function.rs:81:95
81 | fn any < F > ( & mut self , mut f: F ) -> bool where F: FnMut ( Self::Item ) -> bool {}
| ^^ expected bool, found ()

我使用的完整片段是:

fn closure_iterator_any ( v1a: i32 , v1b: i32 , v1c: i32 , v2a: i32 , v2b: i32 , v2c: i32 )
{
pub trait Iterator
{
type Item ; // type of item being iterated over
fn any < F > ( & mut self , mut f: F ) -> bool where F: FnMut ( Self::Item ) -> bool {}
}
let vec1 = vec! [ v1a , v1b , v1c ] ;
let vec2 = vec! [ v2a , v2b , v2c ] ;
println! ( "2 in vector 1: {}" , vec1 . iter () . any ( |&x| x == 2 ) ) ; // iter returns &i32
println! ( "2 in vector 2: {}" , vec2 . into_iter () . any ( |x| x == 2 ) ) ; // into returns i32

let array1 = [ v1a , v1b , v1c ] ;
let array2 = [ v2a , v2b , v2c ] ;
println! ( "2 in array 1: {}" , array1 . iter () . any ( |&x| x == 2 ) ) ;
println! ( "2 in array 2: {}" , array2 . into_iter () . any ( |&x| x == 2 ) ) ;

}

我知道空格过多,在学习一门新语言时我想知道哪里可以放空格,哪里不能。我也不太了解闭包。

最佳答案

在示例中,具有特征的部分,

pub trait Iterator {
// The type being iterated over.
type Item;

// `any` takes `&mut self` meaning the caller may be borrowed
// and modified, but not consumed.
fn any<F>(&mut self, f: F) -> bool
where
// `FnMut` meaning any captured variable may at most be
// modified, not consumed. `Self::Item` states it takes
// arguments to the closure by value.
F: FnMut(Self::Item) -> bool,
{}
}

只是向您展示方法的签名。具体来说,它会告诉您它接受什么参数、它使用什么泛型类型以及它返回什么类型。它并不意味着要执行,而且确实是您所看到的编译错误的来源。

具体的错误是说 any 应该返回 bool 但现在它返回 () (具有唯一的单元类型元素)。这样做的原因都在靠近末尾的小 {} 中。这实际上是一个空函数体,如果它没有返回语句或任何其他可能返回的内容,它将隐式返回 ()

如果您只是想让示例编译,您可以简单地删除该 block (整个 pub trait ... block ),因为它实际上不是示例的一部分。即使您修复并保留它,示例其余部分中使用的 any 也不会是这个,而是定义在 real 上的 any 方法标准库中的 Iterator 特征。

关于使用rust 示例 : closure iterator any gives E0308,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58668873/

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