How to initialize a []u8?

I am a zig newbie.

tmp.zig:76:23: error: type ‘u8’ does not support array initialization syntax const a: u8 = .{1, 3, 5};

Any suggestion is appreciated !

Because []u8 is a slice of u8’s, a slice is a pointer and a length

to specify an array type, you just put the length of the array in the [] e.g. [3]u8

you can also have zig infer the array size with [_]
however, this only works when specifying the type on the value side i.e.

const a = [_]u8{1,2,3];

you also don’t have to specify the variable type since zig can figure it out, if you did, you would have to specify the size anyway since as _ doesn’t work in this position

const a: [_]u8

if you want a slice you can make one from a pointer to an array like this:

const a: []u8 = &[_]u8{1,2,3};

note: you have to specify that a is a slice, otherwise you just get a pointer to an array *[3]u8

in this case zig is smart enough to know that the type your referencing & is an array in this case, meaning you can replace the array type with . to ask zig to figure it out like this

const a: []u8 = &.{1,2,3};

hope I explained it well enough :3

2 Likes

[]T is a slice (a pointer + length pair).

1 Like

$zig version
0.13.0

fn intersection(a: []u8, b: []u8, allocator: std.mem.Allocator) anyerror![]u8 {...}
const a = [_]u8{1, 3, 5};
const b = [_]u8{3, 5, 7, 8, 9};

error: array literal requires address-of operator (&) to coerce to slice type ‘u8’ const intersect = try intersection(a, b, allocator);

const a: []u8 = &[_]u8{1,3,5};
const b: []u8 = &[_]u8{3,5,7,8,9};

error: expected type ‘u8’, found ‘*const [3]u8’ const a: u8 = &[_]u8{1,3,5};

const a: []u8 = &.{1,2,3};
const b: []u8 = &.{3,5,7,8,9};

error: expected type ‘u8’, found ‘*const [3]u8’ const a: u8 = &.{1,2,3};

If intersection does not update a and b you can change it to:

fn intersection(a: []const u8, b: []const u8, allocator: std.mem.Allocator) anyerror![]u8 {...}

You need a var array, because []u8 can update the elements:

    var a = [_]u8{ 1, 3, 5 };
    const pa: []u8 = &a;
2 Likes

you have variables of arrays and you need slices to pass to the function, to get those you have to use &

and

oops i gave bad examples, changing the variable types to []const u8 will fix it, this is because you are creating pointers to literal values which are located in read only memory meaning you can only get a const pointer.

var array = [_]u8{1,2,3};
const a: []u8 = &array;

will work, because it copies the literal value into the variable which is in writable memory so you can now get a mutable pointer to it.

but as @dimdin said, if your function doesn’t mutate parameters it should take const slices

2 Likes

The following idiomatic initialization oftentimes comes handy:

var ary = "hello".*; // copies string literal into variable of type [5:0]u8
ary[0] = 'H'; // change first letter
1 Like