是否可以对字符串字段进行模式匹配?我无法使这段代码工作。
struct Foo {
x: int,
y: int,
str: String
}
pub fn main() {
let a = Foo { x: 1, y: 2 , str: "Hi".to_string()};
match a {
Foo { x: x, y: y, str: "Hi".to_string() } => println!("Found {}, {}", x, y),
_ => {}
}
}
给出这个错误:
<anon>:10:36: 10:37 error: expected one of `,` or `...`, found `.`
<anon>:10 Foo { x: x, y: y, str: "Hi".to_string() } => println!("Found {}, {}", x, y),
^
最佳答案
match
案例可能不包含像 "Hi".to_string()
这样的表达式,只有常量(例如 3
, "Hi
") 或变量(例如 x
)。要匹配 String
字段,您需要使用模式保护:
match a {
Foo { x: x, y: y, str: ref str } if str == &"Hi" =>
println!("Found {}, {}", x, y),
_ => {}
}
if str == &"Hi"
是检查 String
值的模式守卫。请注意,模式保护强制我们使用 ref
来捕获对 String
的引用,而不是将其移出结构。
关于string - 将结构与字符串匹配的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28181112/