【问题标题】:How to handle arrays of different array lengths depending on a condition?如何根据条件处理不同数组长度的数组?
【发布时间】:2023-01-09 06:28:54
【问题描述】:

我的程序中有 2 个不同的数组:

const ARRAY_1: [u8; 2] = [0xe8, 0xe3, 0x37, 0x00];
const ARRAY_2: [u8; 4] = [0xe8, 0xe3];

我想写这样的东西:

if condition1 {
    let ARRAY_CHOSEN: [&[u8]; 2] = ARRAY_1;
}
else if condition2 {
    let ARRAY_CHOSEN: [&[u8]; 4] = ARRAY_2;
}

然后在函数的其余部分使用ARRAY_CHOSEN...但是当然它不起作用,因为ARRAY_CHOSEN包含在嵌套范围内。

如何根据条件选择 2 项或 4 项数组?

【问题讨论】:

    标签: variables rust


    【解决方案1】:

    你可以将它们强制切成片,&[u8]

    const ARRAY_1: [u8; 4] = [0xe8, 0xe3, 0x37, 0x00];
    const ARRAY_2: [u8; 2] = [0xe8, 0xe3];
    
    fn main() {
        let condition1 = false;
        let condition2 = true;
        
        let arr_chosen = if condition1 {
            &ARRAY_1[..]
        } else if condition2 {
            &ARRAY_2[..]
        } else {
            &[]
        };
        
        dbg!(arr_chosen);
    }
    
    [src/main.rs:16] arr_chosen = [
        232,
        227,
    ]
    

    【讨论】:

      【解决方案2】:

      一般来说,这不是惯用 Rust 代码中的可行模式。您有可能为此使用 const 泛型,但如果您是初学者,我建议您不要研究这些泛型,因为它们仅适用于特定的用例。

      只需使用任意大小的 Vec 以及 if 条件作为表达式:

      let chosen = if condition1 {
          vec![1, 2, 3]
      } else if condition2 {
          vec![1, 2, 3, 4, 5, 6]
      } else {
          // you have to provide some default here to cover
          // the case where both condition1 and condition2 are false
          // or you can panic but that is inadvisable
          vec![1, 2, 3]
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-25
        • 1970-01-01
        • 1970-01-01
        • 2018-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-27
        相关资源
        最近更新 更多