Compare these two examples
(from: https://goinbigdata.com/golang-pass-by-pointer-vs-pass-by-value/)
package main
import "fmt"
type Person struct {
firstName string
lastName string
}
func changeName(p Person) {
p.firstName = "Bob"
}
func main() {
person := Person {
firstName: "Alice",
lastName: "Dow",
}
changeName(person)
fmt.Println(person)
}
The code above returns {Alice Dow}
so the struct is not changed.
Now in this example
package main
import "fmt"
func main() {
slice := []string{"a", "b", "c"}
fmt.Println(slice)
updateSlice(slice)
fmt.Println(slice)
}
func updateSlice(slice []string) []string {
slice[0] = "x"
return slice
}
the output is
[a b c]
[x b c]
so the slice was changed by the func updateSlice
.
Would someone explain the difference?