English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang Basic Tutorial

Golang Control Statement

Golang Function & Method

Golang Struct

Golang Slice & Array

Golang String(String)

Golang Pointer

Golang Interface

Golang Concurrency

Golang Exception(Error)

Golang Miscellaneous

Go Slice as Function Parameter

sliceis a mutable length sequence used to store elements of similar types and does not allow different types of elements to be stored in the same slice. Like a slice with index and lengtharraylike, but the size of the slice can be adjusted, unlike arrays that are of fixed size. In the Go language, you can pass a slice tofunction, which means the function gets a copy of the slice.
The slice is passed to the function along with its capacity and length as a value, and the pointer of the slice always points to the base array. Therefore, if we make some changes to the slice passed to the function by value, it will reflect on the slice existing outside the function. Let's discuss this concept with an example:

//Pass a slice to the function
package main
import "fmt"
//the function where the slice is located
//By value
func myfun(element []string) {
    //Modify the given slice
    element[2] = "Java"
    fmt.Println("Modified slice: ", element)
}
func main() {
    //Create a slice
    slc := []string{"C#", "Python", "C", "Perl"}
    fmt.Println("Initial slice: ", slc)
    //Pass the slice to the function
    myfun(slc)
    fmt.Println("Final slice:", slc)
}

Output:

Initial slice: [C# Python C Perl]
Modified slice: [C# Python Java Perl]
Final slice: [C# Python Java Perl]

Usage instructions:In the above example, we have a slice named slc. This slice is passed through the myfun() function. As we know, slice pointers always point to the same reference, even if they are passed within the function. Therefore, when we pass the value C, the index is2When changing to Java. This change also reflects the slice outside the function, so the last modified slice is [c# Python Java perl].

//Pass the slice to the function
package main
import "fmt"
//By value
func myfun(element []string) {
    //Here we only modify the slice
    //using the append function
    //In this case, the function only modifies
    //a copy of the slice existing within it
    //This function does not modify the original slice
    element = append(element, "Java")
    fmt.Println("Modified slice: ", element)
}
func main() {
    //Create a slice
    slc := []string{"C#", "Python", "C", "Perl"}
    fmt.Println("Initial slice: ", slc)
    //Pass the slice
    //To the function
    myfun(slc)
    fmt.Println("Final slice: ", slc)
}

Output:

Initial slice: [C# Python C Perl]
Modified slice: [C# Python C Perl Java]
Final slice: [C# Python C Perl]