Skip to content

Instantly share code, notes, and snippets.

@pyk
Last active August 29, 2015 14:27
Show Gist options
  • Save pyk/4aa55f2c9a04a5df33f4 to your computer and use it in GitHub Desktop.
Save pyk/4aa55f2c9a04a5df33f4 to your computer and use it in GitHub Desktop.
golang "cannot assign to" http://play.golang.org/p/GJWp1G8H-E
package main
import (
"fmt"
)
type A struct {
name string
s []string
}
type B struct {
name string
as map[int]A
}
type C struct {
name string
as map[int]*A
}
func main() {
b := &B{}
b.name = "b"
b.as = make(map[int]A)
// b.as[1] = A{name: "hu"}
// error cannot assign to, because b.as[1] is a
// copy of A{name: "table 1"} and not addressable
// b.as[1].s = append(b.as[1].s, "a")
// proof, the value of b.as[1].s will be nil
// see: https://golang.org/ref/spec#Address_operators
// b2 := b.as[1]
// b2.s = append(b2.s, "hello")
// b2.s = append(b2.s, "world")
// fmt.Printf("%#v\n", b)
// fmt.Printf("%#v\n", b.as[1].s)
// modification must perform on the reference of object
a := A{}
a.name = "a"
a.s = append(a.s, "a")
b.as[1] = a
fmt.Printf("b: %#v\n", b)
// pass A by reference
c := &C{}
c.name = "c"
c.as = make(map[int]*A)
c.as[1] = &A{name: "1"}
c.as[1].s = append(c.as[1].s, "hello")
c.as[1].s = append(c.as[1].s, "world")
fmt.Printf("c: %#v\n", c)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment