[英]Mismatched types error: expected `char`, found reference
the code snippet is:代码片段是:
use std::collections::HashSet;
fn main() {
let dna = String::from("ACCCX");
let dict: HashSet<char> = vec!['A', 'C', 'G', 'T'].into_iter().collect();
println!("{}", dna.chars().all(|&x| dict.contains(x)));
}
the error shown in compilation is:编译中显示的错误是:
error[E0308]: mismatched types
--> src/main.rs:6:37
|
6 | println!("{}", dna.chars().all(|&x| dict.contains(x)));
| ^--
| ||
| |expected due to this
| expected `char`, found reference
| help: did you mean `x`: `&char`
|
= note: expected type `char`
found reference `&_`
Not sure why &x
cannot be inferred as &char
and the links I referred to are:不知道为什么
&x
不能被推断为&char
和我提到的链接是:
Thanks!谢谢!
The error message is a bit confusing, essentially it is backwards.错误消息有点令人困惑,本质上它是倒退的。
dna.chars().all(|&x| dict.contains(x)));
String::chars returns a char
, not &char
, and HashSet::contains expects a reference to the type it contains, so &char
. String::chars 返回一个
char
,而不是&char
,并且 HashSet::contains 期望引用它包含的类型,所以&char
。 However, closure |&x| dict.contains(x)
然而,关闭
|&x| dict.contains(x)
|&x| dict.contains(x)
expects a reference to some type. |&x| dict.contains(x)
期望引用某种类型。
It is a little confusing, but &argument_name
in function parameters essentially performs pattern matching on incoming parameter, dereferencing it.这有点令人困惑,但是 function 参数中的
&argument_name
本质上是对传入参数执行模式匹配,取消引用它。 It is the same as writing |(a, b)|
和写成
|(a, b)|
一样for a closure that takes a two element tuple and immediately destructures it into two variables.对于一个接受两个元素元组并立即将其解构为两个变量的闭包。
So really the message should be Expected reference &_, found char
.所以真正的消息应该是
Expected reference &_, found char
。
Actually I just went to the Rust playground and did what I suggested: First I removed the &
from your |&x|
实际上我只是去了 Rust 操场并按照我的建议做了:首先我从你的
|&x|
中删除了&
. . Then the compiler complained that the
contains(x)
wasn't a reference, so I added a &
there:然后编译器抱怨
contains(x)
不是引用,所以我在那里添加了&
:
use std::collections::HashSet;
fn main() {
let dna = String::from("ACCCX");
let dict: HashSet<char> = vec!['A', 'C', 'G', 'T'].into_iter().collect();
println!("{}", dna.chars().all(|x| dict.contains(&x)));
}
That compiles and prints "false" because X isn't in the hash set.这会编译并打印“false”,因为 X 不在 hash 集中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.