如果你想在一个切片或数组上匹配,你可以通过slice_patterns功能使用&:
slice_patterns
&
#![feature(slice_patterns)] fn main() { let v = vec!["match_this", "1"]; match &v[..] { ["match_this", second] => println!("The second element is {}", second), _ => {}, } }
advanced_slice_patternsgate 让你使用..表明在一个切片的模式匹配中任意数量的元素。这个通配符对一个给定的数组只能只用一次。如果在..之前有一个标识符,结果会被绑定到那个名字上。例如:
advanced_slice_patterns
..
#![feature(advanced_slice_patterns, slice_patterns)] fn is_symmetric(list: &[u32]) -> bool { match list { [] | [_] => true, [x, inside.., y] if x == y => is_symmetric(inside), _ => false } } fn main() { let sym = &[0, 1, 4, 2, 4, 1, 0]; assert!(is_symmetric(sym)); let not_sym = &[0, 1, 7, 2, 4, 1, 0]; assert!(!is_symmetric(not_sym)); }
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8