Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a slice to an array

Tags:

zig

I have a slice that I have guaranteed (in runtime) that its length is at least 8. I want to convert that slice to an array because I need to use std.mem.bytesAsValue() in order to create an f64 from raw bytes (for context, I'm implementing a binary serialization format).

I solved it like this, but I'd like to know if there is a better syntax for achieving the same goal:

    var array: [8]u8 = undefined;
    array[0] = slice[0];
    array[1] = slice[1];
    array[2] = slice[2];
    array[3] = slice[3];
    array[4] = slice[4];
    array[5] = slice[5];
    array[6] = slice[6];
    array[7] = slice[7];
like image 511
André Staltz Avatar asked Sep 26 '26 01:09

André Staltz


1 Answers

you can do this by dereferencing the slice

var array = slice[0..8].*;

or using std.mem.copy

std.mem.copy(u8, &array, slice[0..2]);

while i think you can just need to put slice[0..8] as argument instead creating a variable

like image 93
Ali Chraghi Avatar answered Sep 29 '26 06:09

Ali Chraghi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!