func zero(x int) {
x = 0
}
func main() {
x := 5
zero(x)
fmt.Println(x) // this give your 5
However, when i apply Struct into this scripts
type Circle struct {
x float64
y float64
r float64
}
func circleArea(c Circle) float64 {
c = Circle{0, 0, 1}
return math.Pi * c.r * c.r
}
func main() {
c := Circle{0, 0, 5}
fmt.Println(circleArea(c)) // Interestingly, this gives 3.141592653589793
}
So Here is the confusing part: if we flow the idea of fmt.Println(x) gives the number 5, then fmt.Println(circleArea(c)) should use c.r = 5 instead of c.r = 1. But why they give me 3.1415
In the circleArea function, you are re-assigning the variable c to a new Circle and then using it’s r value and multiplying it by Pi, so it’s not that you are modifying the original c variable, rather you are just returning the result of multiplications on the newly assigned Circle's values before the function has actually returned.
However, if you actually see what is returned, you will see that the original c variable is not affected by the function call.
For example:
package main
import (
"fmt"
"math"
)
type Circle struct {
x float64
y float64
r float64
}
func circleArea(c Circle) float64 {
c = Circle{0, 0, 1}
return math.Pi * c.r * c.r
}
func main() {
c := Circle{0, 0, 5}
fmt.Println(circleArea(c)) // 3.141592653589793
// c is not modified by calling the circleArea function above.
fmt.Println(math.Pi * c.r * c.r) // 78.53981633974483
}