Can array lengths be inferred in Rust?

后端 未结 2 1064
北恋
北恋 2020-12-11 15:16

I can do this:

let a: [f32; 3] = [0.0, 1.0, 2.0];

But why doesn\'t this work?

let a: [f32; _] = [0.0, 1.0, 2.0];

2条回答
  •  青春惊慌失措
    2020-12-11 16:11

    Since 1.39 it's possible using a simple macro

    macro_rules! arr {
        ($id: ident $name: ident: [$ty: ty; _] = $value: expr) => {
            $id $name: [$ty; $value.len()] = $value;
        }
    }
    

    Usage

    arr!(static BYTES: [u8; _] = *b"foo");
    arr!(let floats: [f32; _] = [0., 1.]);
    

提交回复
热议问题