问题描述
我正在尝试使用匹配语句来匹配选项字符串。
let option_string = Some(String::from("Bob"));
match option_string {
Some("Mike") => false,
Some("Bob") => true,
_ => false,
}
很明显,出现了错误expected struct 'String, found '&str'
。
我尝试将其转换为字符串
Some("Mike".to_string()) => false
// Or
Some(String::from("Mike")) => false
但面对另一个错误:'fn'调用在模式中是不允许的
唯一有效的方法是在Some
之前将Mike
放入变量中。
let mike = String::from("Mike");
// and in match
Some(mike) => true,
问题
有没有更加优雅的方式来匹配match
语句中的String
而不是字符串字面值,并且还包含Option
值?
我找到了一个答案,但它看起来并不够优雅。除了创建额外的变量或函数之外,是否只有这一种可能的方法?
option_string.as_deref()
? - Brian61354270option_string.as_deref() == Some("Bob")
优于match
。 - cdhowie