Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Data Types in Go
  • Go Keywords
  • Go Control Flow
  • Go Functions
  • GoLang Structures
  • GoLang Arrays
  • GoLang Strings
  • GoLang Pointers
  • GoLang Interface
  • GoLang Concurrency
Open In App
Next Article:
How to pass a Slice to Function in Golang?
Next article icon

How to pass a Slice to Function in Golang?

Last Updated : 12 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Go, slices are dynamically sized arrays. They are often passed to functions when you want to manipulate or process collections of data. Slices are passed by reference, meaning that any modification made to the slice inside the function will affect the original slice outside the function.

Example

package main

import "fmt"

func printSlice(slice []int) {
fmt.Println("Slice elements:", slice)
}

func main() {
// Initial slice
numbers := []int{1, 2, 3, 4, 5}

// Passing slice to the function
printSlice(numbers)
}

Syntax

func functionName(slice []Type) {
// Function body # Passing Slice to a Function
}

func modifySlice(slice []Type) {
// Modify elements in the slice # Modify Slice Elements inside a function
}

func functionName(slice []Type, element Type) []Type {
// Modify and return the slice # Returning a Slice from a Function
}

func modifySlicePointer(slice *[]Type) {
// Modify the slice through its pointer # Passing a Slice to a Function with a Slice Pointer
}

Table of Content

  • Passing Slice to a function
  • Modifying Slice Elements Inside a Function
  • Returning a Slice from a Function
  • Passing a Slice to a Function with a Slice Pointer

Passing Slice to a function

In Go, slices are passed by reference in terms of the underlying array, meaning any modification to the elements of the slice inside a function will affect the original slice, but changes to the slice’s length or capacity will not affect the original slice outside the function.

Syntax

func functionName(slice []Type) {
// Function body
}

Where:

  • slice: The slice variable you want to pass.
  • Type: The type of elements in the slice (e.g., int, string, etc.).

Example

Go
package main import "fmt"  func printSlice(slice []int) {     fmt.Println("", slice) }  func main() {     // Initial slice     a := []int{1, 2, 3, 4, 5}          printSlice(a) } 

Output
 [1 2 3 4 5] 

Modifying Slice Elements Inside a Function

You can modify the elements of the slice inside the function, and these changes will be reflected in the original slice because slices are passed by reference.

Syntax

func modifySlice(slice []Type) {
// Modify elements in the slice
}

Example

Go
package main import "fmt"  func modifySlice(slice []int) {     for i := range slice {         slice[i] *= 2 // Doubling each element     } }  func main() {     a := []int{1, 2, 3, 4, 5}     fmt.Println("Original slice:", a)      modifySlice(a)          fmt.Println("Modified slice:", a) } 

Output
Original slice: [1 2 3 4 5] Modified slice: [2 4 6 8 10] 

Returning a Slice from a Function

In Go, you can also return a modified slice from a function if needed.

Syntax

func functionName(slice []Type, element Type) []Type {
// Modify and return the slice
}

Example

Go
package main import "fmt"  func addElement(slice []int, element int) []int {     return append(slice, element) }  func main() {     // Initial slice     a := []int{1, 2, 3}          // Adding an element and returning the new slice     newNumbers := addElement(a, 4)          fmt.Println("Original slice:", a)     fmt.Println("New slice:", newNumbers) } 

Output
Original slice: [1 2 3] New slice: [1 2 3 4] 

Passing a Slice to a Function with a Slice Pointer

While slices are already passed by reference, you can also pass a pointer to a slice if you want to modify the slice’s capacity or reassign the slice inside the function.

Syntax

func modifySlicePointer(slice *[]Type) {
// Modify the slice through its pointer
}

Example

Go
package main import "fmt"  func modifySlicePointer(slice *[]int) {     *slice = append(*slice, 6) // Adding an element using pointer }  func main() {     // Initial slice     a := []int{1, 2, 3}     fmt.Println("Original slice:", a)      // Passing slice pointer to the function     modifySlicePointer(&a)          fmt.Println("Modified slice:", a) } 

Output
Original slice: [1 2 3] Modified slice: [1 2 3 6] 

Conclusion

Passing slices to functions in Go is straightforward since they are reference types. You can modify the slice elements within the function, and these changes will be reflected outside the function. You can also pass a slice pointer if you need to modify the slice’s structure, such as appending to it or changing its capacity.


Next Article
How to pass a Slice to Function in Golang?

A

ankita_saini
Improve
Article Tags :
  • Go Language
  • Golang
  • Golang-Slices

Similar Reads

    How to pass an Array to a Function in Golang?
    In Go, arrays are used to store a fixed-length collection of data of the same type. To manage this data effectively, you may often need to pass arrays to functions. In this article we will learn "How to pass an Array to a Function in Golang".Example:Gopackage main import "fmt" // Function to calcula
    2 min read
    How to sort a slice in Golang?
    In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In Go language, you can sort a s
    3 min read
    How to trim a slice of bytes in Golang?
    In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you ar
    3 min read
    How to append a slice in Golang?
    In Go, slices are dynamically-sized, flexible views into the elements of an array. Appending elements to a slice is a common operation that allows for the expansion of the slice as needed. The built-in append function is used to add elements to the end of a slice.In this article,we will learn How to
    2 min read
    How to split a slice of bytes in Golang?
    In Golang, you can split a slice of bytes into multiple parts using the bytes.Split function. This is useful when dealing with data like encoded strings, file contents, or byte streams that must be divided by a specific delimiter.Examplepackage mainimport ( "bytes" "fmt")func main() { // Initial byt
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences