Rust 中的字符串引用比较
String references comparison in 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);
}
Rust 中引用的引用比较总是比较值,从不比较地址。这不仅适用于 &String
,而且适用于 任何 &T
.
例如,这不会编译,因为 Foo
没有实现 PartialEq
,即使我只是比较引用:
struct Foo;
fn main() {
let a = Foo;
let b = Foo;
assert!(&a == &b);
}
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`
引用的PartialEq
实现是
impl<'_, '_, A, B> PartialEq<&'_ B> for &'_ A where
A: PartialEq<B> + ?Sized,
B: ?Sized,
可以看到检查&A == &B
需要能够做到A == B
.
我刚刚确认了 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);
}
Rust 中引用的引用比较总是比较值,从不比较地址。这不仅适用于 &String
,而且适用于 任何 &T
.
例如,这不会编译,因为 Foo
没有实现 PartialEq
,即使我只是比较引用:
struct Foo;
fn main() {
let a = Foo;
let b = Foo;
assert!(&a == &b);
}
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`
引用的PartialEq
实现是
impl<'_, '_, A, B> PartialEq<&'_ B> for &'_ A where
A: PartialEq<B> + ?Sized,
B: ?Sized,
可以看到检查&A == &B
需要能够做到A == B
.