[英]Match a slice of str or String
我有一個 function 可以采用&[&str]
或&[String]
並根據切片返回不同的值。 如果我添加PartialEq
約束,使用==
可以正常工作:
pub fn info1<'a, S>(path: &[S]) -> Option<String>
where
S: PartialEq<&'a str>,
{
if path == ["a", "b"] {
return Some("It's a-b!".to_string())
}
None
}
但是如果我使用match
它將不起作用:
pub fn info2<'a, S>(path: &[S]) -> Option<String>
where
S: PartialEq<&'a str>,
{
match path {
["a", "b"] => Some("It's a b!".to_string()),
_ => None,
}
}
error[E0308]: mismatched types
--> src/lib.rs:16:6
|
11 | pub fn info2<'a, S>(path: &[S]) -> Option<String>
| - this type parameter
...
15 | match path {
| ---- this expression has type `&[S]`
16 | ["a", "b"] => Some("It's a b!".to_string()),
| ^^^ expected type parameter `S`, found `&str`
|
= note: expected type parameter `S`
found reference `&'static str`
有什么辦法讓它工作嗎? 理想情況下不需要["a".as_foo(), "b".as_foo()]
。
您不能為此使用match
。
您的第一個版本沒有任何問題。 您可以使用更高級別的特征綁定( for<'a>
)使其更通用:
pub fn info1<S>(path: &[S]) -> Option<String>
where
for<'a> S: PartialEq<&'a str>,
{
if path == ["a", "b"] {
Some("It's a-b!".to_string());
} else {
None
}
}
我從 Rust 論壇得到了有用的答案。 不可能使用match
,因為match
中的模式只能由struct
s、 enum
s、 slice
s 和文字組成。 我發現的最好的描述在這里:
一個模式由以下一些組合組成:
- 字面量
- 解構 arrays、枚舉、結構或元組
- 變量
- 通配符
- 占位符
在這種情況下,像"a"
這樣的字符串文字是&str
,所以這確實是您可以match
的唯一類型的字符串(您可以看到人們有基本相同的問題,但這里沒有切片)。 在這種情況下,您可以在不分配的情況下解決它,因為您不需要構造一片引用 - 您只需要一個。
由於您肯定需要一片&str
,因此除了按照Skysch 的建議分配Vec<&str>
之外,別無他法:
pub fn info1<'a, S>(path: &[S]) -> Option<String>
where
S: AsRef<str>,
{
match &path.iter().map(|s| s.as_ref()).collect::<Vec<_>>()[..] {
["a", "b"] => Some("It's a b!".to_string()),
_ => None,
}
}
我認為即使使用macro_rules!
您無法使用match
解決它。 但是,可以制作一個類似match
的宏,它使用==
代替。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.