Home > Article > Backend Development > How to pass golang function parameters
There are three ways to pass function parameters in Go: by value, by reference, and by pointer. The default is to pass by value, pass by reference needs to use pointer type, pass by pointer directly pass the pointer. When you need to modify external variables or share data efficiently, use pass by reference or by pointer respectively.
How to pass Go function parameters
Go function parameters can be passed by value, reference or pointer. Choosing the correct passing method is critical to ensuring that your function functions properly and avoids unnecessary memory allocations.
Pass by value
This passing method passes a copy of the function parameters to the function. Any changes made to the copy will not affect the original variable. It is the default delivery method.
For example:
func changeValue(x int) { x++ } func main() { a := 5 changeValue(a) fmt.Println(a) // 输出:5 }
Pass by reference
Pass by reference uses the address of the parameter, not a copy. Therefore, any changes made to the parameters will affect the original variables. To pass parameters by reference, you need to use pointer types (*).
For example:
func changeRef(x *int) { *x++ } func main() { a := 5 changeRef(&a) fmt.Println(a) // 输出:6 }
Pass by pointer
Pass by pointer is similar to pass by reference, but it passes the pointer directly itself rather than the address. This passing method helps share data efficiently between functions because it avoids memory allocation.
For example:
type Node struct { value int next *Node } func changePtr(node *Node) { node.value++ } func main() { root := &Node{5, nil} changePtr(root) fmt.Println(root.value) // 输出:6 }
Practical case:
Consider a function that handles file input and output. This function converts the file into Path and file contents as parameters. Passing the file path by reference saves the overhead of creating a new copy.
func processFile(path string, contents []byte) { // 处理文件 path 和内容 contents } func main() { path := "myfile.txt" contents := readFile() processFile(path, contents) // 后续处理 }
Which delivery method to choose
Which delivery method to choose depends on the purpose and performance requirements of the function:
The above is the detailed content of How to pass golang function parameters. For more information, please follow other related articles on the PHP Chinese website!