其他分享
首页 > 其他分享> > rust 变参

rust 变参

作者:互联网

#[derive(Clone, Copy)]
enum Args<'a> {
    Idx(usize),
    IdxList(&'a [usize]),
}

fn get_data<'a, T>(arr: &'a [T], idxs: Args<'a>) -> Vec<&'a T> {
    match idxs {
        Args::Idx(idx) => vec![&arr[idx]],
        Args::IdxList(idxs) => idxs.iter().map(|&idx| &arr[idx]).collect(),
    }
}

fn main() {
    let a = ["zhihu", "baidu", "360", "996"];
    assert!(get_data(&a, Args::Idx(1)) == vec![&a[1]]);
    assert!(get_data(&a, Args::IdxList(&[1, 2, 3])) == vec![&a[1], &a[2], &a[3]]);
}

可以这样实现。对于这种多下标访问的,更常见处理方式的是使用变参宏实现,比如以下这个库

https://github.com/rodrimati1992/multindex

use multindex::multindex;

const ROW_SIZE: usize = 5;

let array: [u16; ROW_SIZE * 4] = [
    1, 2, 3, 5, 8,
    13, 21, 34, 55, 89,
    144, 233, 377, 610, 987,
    1597, 2584, 4181, 6765, 10946,
];


type Row = [u16; ROW_SIZE];
// The type annotation is for the reader, the type can be inferred.
let (row0, row1, row2, row3): (&Row, &Row, &Row, &Row) =
    multindex!(array; ..ROW_SIZE, ..ROW_SIZE * 2, ..ROW_SIZE * 3, ..ROW_SIZE * 4);

assert_eq!(row0, &[1, 2, 3, 5, 8]);
assert_eq!(row1, &[13, 21, 34, 55, 89]);
assert_eq!(row2, &[144, 233, 377, 610, 987]);
assert_eq!(row3, &[1597, 2584, 4181, 6765, 10946]);

  

标签:变参,Args,assert,idxs,Row,ROW,rust,SIZE
来源: https://www.cnblogs.com/pythonClub/p/16484806.html