Can I pass params as an array?

99封情书 提交于 2020-05-29 15:43:50

问题


E.g., instead of

assert_eq!(add(2,3), 5);

is there some way to call something like

let params: [u32; 2] = [2 ,3];
assert_eq!(call!(&add, params), 5);

I would find this functionality very useful for testing. E.g., if I want to write multiple tests for a function that takes a large number of params, I want to be able to reuse a dummy param object like this:

#[cfg(test)]
mod tests {
    const dummy: [u32; 5] = [0, 0, 0, 0, 0]; 

    #[test]
    fn test_first_param() {
        let mut params = dummy;
        params[0] = 1;
        assert_eq!(call!(&add, params)), 1);
    }

    #[test]
    fn test_second_param() {
        let mut params = dummy;
        params[1] = 1;
        assert_eq!(call!(&add, params)), 1);
    }
}

Edit:

If this functionality does not exist, would anyone be interested in me making and publishing a macro?


回答1:


There's no feature in the language that enumerates over an array and passes each element as an argument. You're correct that you'd need a macro.



来源:https://stackoverflow.com/questions/60329701/can-i-pass-params-as-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!