Home >Backend Development >Golang >How are Golang function parameters passed?
In Go, there are three ways to pass function parameters: pass by value (value or copy), pass by reference (pointer), and pass by immutable reference (structure/array reference, unmodifiable object). When passed by value, the function operates on a copy of the value and does not affect the original value; when passed by reference, the function can modify the original value; when passed by immutable reference, the function can operate on the fields of the object, but does not modify the object itself. These three methods are suitable for different scenarios. For example, passing by value is suitable for read-only operations, passing by reference is suitable for modification operations, and passing by immutable reference is suitable for operating fields of structures/arrays.
Go function parameter passing mechanism
In the Go language, function parameters are passed in three main ways:
Pass by value
When you pass a parameter by value, a copy of the parameter value is passed. Any modification to this value only affects the copy within the function, not the original value.
func modifyValue(num int) { num *= 2 } func main() { x := 10 modifyValue(x) fmt.Println(x) // 输出:10 }
Pass by reference
If you want to allow a function to modify the passed value, you can use pointer pass by reference. This is accomplished by declaring a pointer parameter using the *
prefix.
func modifyReference(num *int) { *num *= 2 } func main() { x := 10 modifyReference(&x) fmt.Println(x) // 输出:20 }
Passing by immutable reference
Structures and arrays can be passed by passing their immutable reference. This allows the function to access the fields of the structure or array, but not modify the object itself.
type Point struct { x int y int } func modifyPoint(p Point) { p.x *= 2 } func main() { point := Point{10, 20} modifyPoint(point) fmt.Println(point) // 输出:{20 20} }
Practical case
Suppose we have a function calculateTotalCost
, its function is to calculate their total cost given a list of items.
import "fmt" type Item struct { name string price float64 } func calculateTotalCost(items []Item) float64 { total := 0.0 for _, item := range items { total += item.price } return total } func main() { items := []Item{ {"Item 1", 10.00}, {"Item 2", 20.00}, {"Item 3", 30.00}, } totalCost := calculateTotalCost(items) fmt.Println(totalCost) // 输出:60.00 }
In this case, items
is passed as a slice by value. This means that the function will receive a copy of the items
variable without modifying the original slice.
The above is the detailed content of How are Golang function parameters passed?. For more information, please follow other related articles on the PHP Chinese website!