How to initialize a slice?


( I am at the very beginning of programming in Zig and I am using Linux only. And I am no native English speaker… :wink:

The documentation I found on the internet regarding Zig always creates a slice from an array, which in turn was created from a string (for example…which meets my usecase…).

Is there a way to directly initialize a slice from a constant string and if “TRUE” - how can I do that?


EDIT/PS: I am using Zig compiled from HEAD/repo, updated daily…

Doesn’t this work?

const msg: []const u8 = "hello";

Sorry … may be dumb question ahead:
…looks like the initialization of an array to my (untrained) eyes…or…?

No, []T (or []const T depending on constness) indicates a slice. An array needs a fixed size so you’d declare it with e.g. [5]u8, [_]u8 if the length can be inferred from its initialization.

Compare the language reference on Arrays and Slices.

Then I would think, that

const msg: []const u8 = “hello”;

is a slice, where

const msg: [_]const u8 = “hello”;

would be an array, since in both cases the size/length can be determined at compile time…

Pretty much, though there was an error in my previous post (can’t const array child types, so it can be [N]T but not [N]const T) and inferring the length doesn’t work when assigning it from a string.

$ cat demo.zig 
const std = @import("std");

pub fn main() void {
    const msg_arr: [5]u8 = "hello".*;
    const msg_slc: []const u8 = &msg_arr;
    std.debug.print("msg_arr: {s} ({*})\n", .{ msg_arr, &msg_arr });
    std.debug.print("msg_slc: {s} ({*})\n", .{ msg_slc, msg_slc });

$ zig run demo.zig
msg_arr: hello ([5]u8@202ca0)
msg_slc: hello (u8@202ca0)

As you will see, the slice is a pointer to the same address as the array. The array has a storage size on the stack, the slice only stores the pointer to the actual data.

1 Like

Thanks a lot, jmc for explaining this to me…!
Helps me a lot - very appreciated! :slight_smile: