call by value / call by reference
package main
import (
"fmt"
)
type foo struct {
a, b, c int
}
func main() {
f := foo{a: 1, b: 2, c: 3}
fmt.Println(f)
bar(f)
fmt.Println(f)
}
func bar(f foo) {
f.a = -1
}
package main
import (
"fmt"
)
type foo struct {
a, b, c int
}
func main() {
f := foo{a: 1, b: 2, c: 3}
fmt.Println(f)
bar(&f)
fmt.Println(f)
}
func bar(f *foo) {
f.a = -1
}
package main
import (
"fmt"
)
type foo struct {
a, b, c int
}
func main() {
f := []foo{
{a: 1, b: 2, c: 3},
{a: 10},
}
fmt.Println(f)
change_struct(f)
fmt.Println(f)
}
func change_struct(f []foo) {
for i := range f {
f[i].a = -1
}
}
package main
import (
"fmt"
)
type foo struct {
a, b, c int
}
func main() {
f := []foo{
{a: 1, b: 2, c: 3},
{a: 10},
}
fmt.Println(f)
change_struct(f)
fmt.Println(f)
}
func change_struct(f []foo) {
for i := 0; i < len(f); i++ {
f[i].a = -1
}
}
package main
import (
"fmt"
)
type foo struct {
a, b, c int
}
func main() {
f := []*foo{
{a: 1, b: 2, c: 3},
{a: 10},
}
fmt.Println(f[0], f[1])
change_struct(f)
fmt.Println(f[0], f[1])
}
func change_struct(f []*foo) {
for _, x := range f {
x.a = -1
}
}
package main
import (
"fmt"
)
type foo struct {
a, b, c int
}
func main() {
f := []*foo{
{a: 1, b: 2, c: 3},
{a: 10},
{a: 1, b: 2, c: 3},
}
fmt.Println(f)
f = change_struct(f)
fmt.Println(f)
}
func change_struct(f []*foo) []*foo {
y := []*foo{}
fmt.Println(f, y)
for _, x := range f {
if x.b == 2 {
y = append(y, x)
}
}
fmt.Println(f, y)
return y
}
Reference