我不希望以下代码工作,但作为语法探索的一部分,我在操场上尝试:
fn main() {
struct EOF {};
let lines = vec![Ok("line 1"), Ok("line 2"), Err(EOF {})];
for Ok(line) in lines {
println!("{}", line);
}
}
Run Code Online (Sandbox Code Playgroud)
错误消息是
error[E0005]: refutable pattern in `for` loop binding: `Err(_)` not covered
--> src/main.rs:4:9
|
4 | for Ok(line) in lines {
| ^^^^^^^^ pattern `Err(_)` not covered
Run Code Online (Sandbox Code Playgroud)
根据上面的消息,看起来我只需要为Err案例添加一个匹配臂.但这样做的正确语法是什么?
当循环遍历一个结构片段时,我得到的值是一个引用(这很好),但是在某些情况下,必须var像(*var)在很多地方一样编写它是很烦人的.
有没有更好的方法来避免重新声明变量?
fn my_fn(slice: &[MyStruct]) {
for var in slice {
let var = *var; // <-- how to avoid this?
// Without the line above, errors in comments occur:
other_fn(var); // <-- expected struct `MyStruct`, found reference
if var != var.other {
// ^^ trait `&MyStruct: std::cmp::PartialEq<MyStruct>>` not satisfied
foo();
}
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅:实际错误输出(更加神秘).
在迭代元组列表时,&需要使其工作.这样就行了......
for &(a, b, c) in [("hello", 1.0, 5), ("world", 2.0, 2)].iter() {
println!("{} {} {}", a, b, c);
}
Run Code Online (Sandbox Code Playgroud)
但那不会......
for (a, b, c) in [("hello", 1.0, 5), ("world", 2.0, 2)].iter() {
println!("{} {} {}", a, b, c);
}
// type mismatch resolving `<core::slice::Iter<'_, (&str, _, _)> as core::iter::Iterator>::Item == (_, _, _)`:
// expected &-ptr,
found tuple [E0271]
Run Code Online (Sandbox Code Playgroud)
我确信它与我尚未完全内化的解构语法的复杂性有关.
你能解释一下&符背后的句法真相吗?