Learn

All of this array and slice functionality is useful, but we need to be able to use it outside of main. In this exercise, we will learn to define functions which allow us to repeat functionality using arrays or slices.

We can pass arrays or slices into functions as parameters. To pass an array parameter into a function, we provide a local name, square brackets, and the data type. The difference between slice and array parameters is whether the number of elements is stated:

func printFirstLastArray(array [4]int) { fmt.Println("First", array[0]) fmt.Println("Last", array[3]) } func printFirstLastSlice(slice []int) { length := len(slice) if (length > 0) { fmt.Println("First", slice[0]) fmt.Println("Last", slice[length-1]) } }

Due to Go being a pass by value language, modifying a normal array parameter won’t create permanent change. Sometimes this can be useful in performing local calculations.

// Changes to the array will only be local to the function func changeFirst(array [4]int, value int) { array[0] = value }

In order to retain changes, a slice can be used:

// Changes to the array parameter will be permanent func changeFirst(slice []int, value int) { if (len(slice) > 0) { slice[0] = value } }

Let’s practice using arrays in our functions!

Instructions

1.

To practice passing slices into functions, let’s complete this function that changes the last elements of our myTutors string slice to a specified value. In between the parentheses in the function declaration, define the function to take in a slice parameter and a string.

2.

Now, let’s change the last element of the slice to the new string value. The last element will be at the index of the length minus one.

3.

Now, in the same function, print the slice to show that the slice has been modified with the new name.

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?