dictionary - Deleting pointer value doesn't panic -
why doesn't following code panic? test
pointer. fmt.println(people[0].name)
instead of fmt.println(test.name)
panic.
package main import "fmt" func main() { type person struct { id int name string } people := make(map[int]*person) people[1] = &person{0, "name"} fmt.println(people[0].name) test := people[0] test.name = "name2" fmt.println(test.name) people[0].name = "name3" fmt.println(test.name) delete(people, 0) fmt.println(test.name) }
the use of builtin delete()
removes entry map. not delete / deallocate memory pointed value associated removed key.
in go can't manage memory this, go garbage collected language , freeing memory duty , responsibility of garbage collector.
your code doesn't panic because have (valid) pointer value of type person
, , long have it, person not become invalid (its memory not freed).
when change code people[0].name
, indexing map key not in map (because removed delete()
), result of index expression zero value of value type of map, nil
*person
type. , attempting refer name
field of nil
struct pointer cause runtime panic.
Comments
Post a Comment