Zig NEWS

Cover image for Mutable Global Data in Zig
David Vanderson
David Vanderson

Posted on

Mutable Global Data in Zig

Sometimes you want to write a small test file, or some example code, that shows how to mutate a string or slice of data.

But how do you make a global mutable var prefilled with example data?

The recipe is:

  1. make a const array of the example data
  2. make a var that copies that data
const std = @import("std");

// strings
const data_str = "hello";
var mut_str = data_str.*; // deref string to get array

// struct arrays
const foo = struct {
    ord: enum { first, second },
};
const data_foo = [_]foo{ .{ .ord = .first }, .{ .ord = .second } };
var mut_foo = data_foo;

pub fn main() !void {

    // upcase string
    for (0..mut_str.len) |i| {
        mut_str[i] = std.ascii.toUpper(mut_str[i]);
    }

    std.debug.print("{s}\n", .{mut_str});

    // swap foos
    const temp = mut_foo[0];
    mut_foo[0] = mut_foo[1];
    mut_foo[1] = temp;

    for (mut_foo, 0..) |f, i| {
        std.debug.print("foo[{d}]: {s}\n", .{ i, @tagName(f.ord) });
    }
}
Enter fullscreen mode Exit fullscreen mode

Took me too long to figure this out. Hope it helps!

Here's me asking about it on ziggit.dev

Top comments (2)

Collapse
 
jrfondren profile image
jrfondren

You can also deref the string literal:

var mut_str = "hello".*;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
david_vanderson profile image
David Vanderson

Yes good point - many times you can combine the const data and var declaration onto a single line.