How to pass a Slice to Function in Golang?


Golang, also known as Go, is a popular programming language that is known for its simplicity, efficiency, and performance. Slices are an important data structure in Golang that allows us to work with a sequence of elements of the same type. In this article, we'll discuss how to pass a slice to a function in Golang, and provide a step-by-step guide on how to achieve this task.

What is a Slice in Golang?

A slice in Golang is a dynamic array, which means it can grow or shrink as needed. It's a powerful data structure that allows us to work with a sequence of elements of the same type, and is commonly used in Golang programs to manage collections of data.

Why Pass a Slice to a Function?

In many cases, we need to pass a slice to a function to perform operations on the elements of the slice. For instance, when we're building a data processing application that requires sorting or filtering of data, or when we need to manipulate the elements of a slice in some way.

How to Pass a Slice to a Function in Golang?

In Golang, we can pass a slice to a function by simply passing the slice as an argument to the function. The function can then work with the elements of the slice as needed.

Example

Here's an example of how to pass a slice to a function −

package main

import "fmt"

func main() {
   numbers := []int{1, 2, 3, 4, 5}
   result := sum(numbers)
   fmt.Println(result)
}

func sum(numbers []int) int {
   sum := 0
   for _, number := range numbers {
      sum += number
   }
   return sum
}

Output

15

In the above example, we first declare a slice of integers numbers with the values 1, 2, 3, 4, and 5. Then we call the sum() function and pass the numbers slice as an argument. The sum() function then calculates the sum of the elements of the slice and returns the result. Finally, we print the result to the console using the Println() function.

Conclusion

In this article, we discussed how to pass a slice to a function in Golang. We learned that a slice in Golang is a dynamic array that allows us to work with a sequence of elements of the same type, and that we can pass a slice to a function by simply passing the slice as an argument. By following the step-by-step guide provided in this article, you should now be able to easily pass slices to functions in your Golang programs.

Updated on: 08-May-2023

844 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements