When I compile the following code snippet:
struct Packet([u8; 4]);
impl Packet {
const fn from(labels: [&[u8; 2]; 2]) -> Packet {
let mut bytes = [0; 4];
bytes[..2].copy_from_slice(labels[0]);
bytes[2..].copy_from_slice(labels[1]);
Packet(bytes)
}
}
const AA: &[u8; 2] = b"AA";
const BB: &[u8; 2] = b"BB";
const CC: &[u8; 2] = b"CC";
const AABB: Packet = Packet::from([AA, BB]);
const AACC: Packet = Packet::from([AA, CC]);
I get the following compiler error:
error[E0723]: mutable references in const fn are unstable
--> src/main.rs:7:9
|
7 | bytes[..2].copy_from_slice(labels[0]);
| ^^^^^^^^^^
|
= note: see issue #57563 <https://github.com/rust-lang/rust/issues/57563> for more information
= help: add `#![feature(const_fn)]` to the crate attributes to enable
The error is very clear: mutable references in const fn are not yet part of stable Rust. But maybe there's a way to achieve that in stable Rust without using mutable references?
I know I could do this instead:
const AABB: Packet = Packet(*b"AABB");
const AACC: Packet = Packet(*b"AACC");
But in this case, I'm not reusing the "AA" constant which is precisely what I'm trying to achieve.
Thanks for any help on this matter!
You can use an array literal and supply the values like so:
impl Packet {
const fn from(labels: [&[u8; 2]; 2]) -> Packet {
let bytes = [labels[0][0], labels[0][1], labels[1][0], labels[1][1]];
Packet(bytes)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With