duanguochong0397 2017-08-15 09:28
浏览 31

删除指针值不会死机

Why doesn't the following code panic? test is definitely a pointer. With fmt.Println(people[0].Name) instead of fmt.Println(test.Name) it does 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)
}

Playground

  • 写回答

1条回答 默认 最新

  • drjk87189 2017-08-15 09:33
    关注

    The use of the builtin delete() removes an entry from a map. It does not delete / deallocate the memory pointed by the value associated with the removed key.

    In Go you can't manage memory like this, Go is a garbage collected language and freeing memory is the duty and responsibility of the garbage collector.

    Your code doesn't panic because you have a (valid) pointer to a value of type Person, and as long as you have it, that person will not become invalid (its memory will not be freed).

    When you change your code to people[0].Name, then you are indexing a map with a key which is not in the map (because you just removed it with delete()), so the result of the index expression will be the zero value of the value type of the map, which is nil for the *Person type. And attempting to refer to the Name field of a nil struct pointer will cause a runtime panic.

    评论

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路