Stationary static array of rust

I am trying to initialize a struct like this:

struct BytePattern {
    pattern: &'static [u8],
    mask: &'static [u8]
};

      

Is it possible to initialize this line like:

return BytePattern {
    pattern: &'static [0x00u8, 0x00u8, 0x01u8, 0x00u8],
    mask:  &'static  [0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8]
}

      

Edit: the above syntax returns `error: expected :, found '['

Edit: Reddit has provided the following hack to do this (yes, I'll jerk and ask in multiple places for this language)

return BytePattern {
    pattern: { static P: &'static [u8] = &[0x00u8, 0x00u8, 0x01u8, 0x00u8]; P },
    mask:    { static M: &'static [u8] = &[0xFFu8, 0xFFu8, 0xFFu8, 0xFFu8]; M },
}

      

Which is ... terrible, but it works. I will use it if I cannot find something else

+3


source to share


1 answer


You can use byte string literals to create &'static [u8]

:

BytePattern {
    pattern: b"\x00\x00\x01\x00",
    mask:  b"\xff\xff\xff\xff",
}

      



This is of course not a generic solution for any static slices, but takes care of the case u8

.

+1


source







All Articles