# Mutating elements in a slice during a for loop

**URL:** <https://ziggit.dev/t/mutating-elements-in-a-slice-during-a-for-loop/2691>\
**Category:** Help\
**Created:** [January 3, 2024, 12:55am UTC](https://ziggit.dev/t/mutating-elements-in-a-slice-during-a-for-loop/2691 "2024-01-03T00:55:30Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![braddabug](https://ziggit.dev/letter_avatar_proxy/v4/letter/b/a587f6/32.png) [@braddabug](https://ziggit.dev/u/braddabug)\
**Post date:** [January 3, 2024, 12:55am UTC](https://ziggit.dev/t/mutating-elements-in-a-slice-during-a-for-loop/2691/1 "2024-01-03T00:55:30Z")

</div>

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

```zig
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:

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

```

Or is the only alternative to write something like:

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

```

---

<div class="post-metadata">

**Author:** ![00JCIV00](https://ziggit.dev/user_avatar/ziggit.dev/00jciv00/32/1069_2.png) [@00JCIV00](https://ziggit.dev/u/00JCIV00)\
**Post date:** [January 3, 2024, 1:15am UTC](https://ziggit.dev/t/mutating-elements-in-a-slice-during-a-for-loop/2691/2 "2024-01-03T01:15:05Z")

</div>

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

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

```

---

<div class="post-metadata">

**Author:** ![braddabug](https://ziggit.dev/letter_avatar_proxy/v4/letter/b/a587f6/32.png) [@braddabug](https://ziggit.dev/u/braddabug)\
**Post date:** [January 3, 2024, 1:36am UTC](https://ziggit.dev/t/mutating-elements-in-a-slice-during-a-for-loop/2691/3 "2024-01-03T01:36:00Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![squeek502](https://ziggit.dev/user_avatar/ziggit.dev/squeek502/32/409_2.png) [@squeek502](https://ziggit.dev/u/squeek502)\
**Post date:** [January 3, 2024, 2:16am UTC](https://ziggit.dev/t/mutating-elements-in-a-slice-during-a-for-loop/2691/4 "2024-01-03T02:16:10Z")

</div>

Relevant docs for future reference: [Documentation - The Zig Programming Language](https://ziglang.org/documentation/master/#for) (the `"for reference"` test)
