Learn

Being able to retrieve the values stored in our array is super helpful, but what if we need to change them? Changing an array value is something that happens all the time in professional programs. Consider:

  • Counting or calculating a value over time
  • Recieving new information about a piece of data
  • Having data change positions within the array

All of these scenarios require that we change the value initially stored in our array. The syntax for doing so is quite simple

array[index] = value

Where index is any valid index in the array, value is any expression we want. Let’s say we had an array:

myArray := [4]int{10, 24, 5, 47}

Let’s say that we decide we want the third element to now be 33. We could change the array at that index with the following line:

myArray[2] = 33

The content of the array would now be {10, 24, 33, 47}

We can use this syntax to modify any valid index, between 0 and the length of the array.

In the next exercise, we will learn about slices, which allow us to add additional length to our lists, but for now, let’s practice modifying elements!

Instructions

1.

We tried to create an array with a list of our dog’s names, but we must have turned off autocorrect!

Our second dog’s name is Fido, not Fedo.

Can you use the array element manipulation syntax we just learned to fix it?

2.

We can’t believe we messed up the other dog name too!

Our third dog is Jeff not Jegf.

Can you fix that using the array manipulation syntax?

3.

Let’s check our work.

Please print the array of dog names.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?