Mutating elements in a slice during a for loop

I want to iterate over a slice and change each item’s value. Without thinking I wrote something like this:

fn doubleAll(items: []i32) {
	for (items) |item| {
		item *= 2;
	}
}

But then I quickly realized that won’t work. Is there an easy syntactical way to tell Zig I want a pointer to each item in the slice, and not a copy? Something like:

fn doubleAll(items: []i32) {
	for (items) |*item| {
		*item *= 2;
	}
}

Or is the only alternative to write something like:

fn doubleAll(items: []u32) {
	var i : usize = 0;
	while(i < items.len) : (i += 1) {
		items[i] *= 2;
	}
}
1 Like

Your second way is almost right, but you’ll want to dereference item within the loop like this:

fn doubleAll(items: []i32) {
	for (items) |*item| {
		item.* *= 2;
	}
}
7 Likes

Wow, I almost had it. I gave up too soon. Thanks!

2 Likes

Relevant docs for future reference: Documentation - The Zig Programming Language (the "for reference" test)

3 Likes