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:
- make a const array of the example data
- 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) });
}
}
Took me too long to figure this out. Hope it helps!
Top comments (2)
You can also deref the string literal:
Yes good point - many times you can combine the const data and var declaration onto a single line.