fx-*_*rin 3 string comparison rust
我刚刚确认了Vec::contains工作原理。我在下面写了代码,看起来工作正常。
但我不知道它为什么有效,因为它比较&String类型。这是否意味着即使没有取消引用字符串比较也有效?
struct NewStruct {
string_vec: Vec<Option<String>>,
}
fn main() {
let mut mys = NewStruct {
string_vec: Vec::<Option<String>>::new(),
};
mys.string_vec.push(Some("new array".to_string()));
let ref_st = mys.string_vec.iter().filter(|o|o.is_some()).map(|o|o.as_ref().unwrap()).collect::<Vec<&String>>();
println!("result:{:?}", ref_st.contains(&&("some string".to_string())));
println!("result:{:?}", ref_st.contains(&&("new array".to_string())));
println!("Hello, world!");
f64::from(1234_u64 as i32);
}
Run Code Online (Sandbox Code Playgroud)
Rust 中引用的引用比较总是比较值,而不是地址。这不只是为是真实的&String,但对于任何 &T。
例如,这不会编译,因为即使我只是比较引用Foo也不会实现PartialEq:
struct Foo;
fn main() {
let a = Foo;
let b = Foo;
assert!(&a == &b);
}
Run Code Online (Sandbox Code Playgroud)
error[E0369]: binary operation `==` cannot be applied to type `&Foo`
--> src/main.rs:7:16
|
7 | assert!(&a == &b);
| -- ^^ -- &Foo
| |
| &Foo
|
= note: an implementation of `std::cmp::PartialEq` might be missing for `&Foo`
Run Code Online (Sandbox Code Playgroud)
PartialEq引用的实现是
struct Foo;
fn main() {
let a = Foo;
let b = Foo;
assert!(&a == &b);
}
Run Code Online (Sandbox Code Playgroud)
您可以看到检查&A == &B需要能够做到A == B。
| 归档时间: |
|
| 查看次数: |
409 次 |
| 最近记录: |