How to get a slice as a fixed-size array in Rust?
Hello! I started learning Rust and encountered a problem that seems simple, but I can't find an elegant solution.\n\nI have a slice from a vector or another array, for example `&[u8]`. I need to convert it to a fixed-size array, for example `[u8; 4]`. In other languages, I would just cast types or take the first N elements, but in Rust everything is strict with types.\n\nHere's an example that doesn't work:\n\n```rust\nfn main() {\n let data: Vec = vec![1, 2, 3, 4, 5];\n let slice: &[u8] = &data[0..4];\n \n // Want to get array [u8; 4]\n let array: [u8; 4] = slice; // Error: expected array `[u8; 4]`, found `&[u8]`\n}\n```\n\nI know I can manually copy each element, but it looks ugly:\n\n```rust\nlet mut array: [u8; 4] = [0; 4];\nfor (i, &val)
No answers yet.
Log in to leave an answer
Blogs