dongyu9667 2014-01-31 05:58
浏览 24
已采纳

追加到结构片时无效的内存地址或nil指针取消引用

package main

import (
    "fmt"
)

type Person struct {
    name    string
}

func main() {
    p := make([]*Person, 0)
    p = append(p, &Person{"Brian"})
    fmt.Println(p[0].name)
    p = append(p, &Person{"Le Tu"})
    fmt.Println(p[1].name)
}

The above works fine.

package main

import (
    "fmt"
)

type Person struct {
    name    string
}

func main() {
    p := make([]*Person, 1) //Changed to 1 instead of 0
    p = append(p, &Person{"Brian"})
    fmt.Println(p[0].name)
    p = append(p, &Person{"Le Tu"})
    fmt.Println(p[1].name)
}

The above panics.

My understanding of append was that it hid the mechanics of extending/adding. Clearly, my mental model of using append as a sort of "push" for slices is incorrect. Can anyone explain to me why the second sample above panics? Why can't I just append my struct?

  • 写回答

2条回答 默认 最新

  • duanpaotian2348 2014-01-31 06:16
    关注

    For example,

    package main
    
    import (
        "fmt"
    )
    
    type Person struct {
        name string
    }
    
    func main() {
        p := make([]*Person, 1) //Changed to 1 instead of 0
        fmt.Println(len(p), p)
        p = append(p, &Person{"Brian"})
        fmt.Println(len(p), p)
        fmt.Println(p[1].name)
        fmt.Println(p[0])
        fmt.Println(p[0].name)
    }
    

    Output:

    1 [<nil>]
    2 [<nil> 0x10500190]
    Brian
    <nil>
    panic: runtime error: invalid memory address or nil pointer dereference
    

    p has length 1 before the append, length 2 after. Therefore, p[0] has the uninitialized pointer value nil and p[0].name is invalid.

    The Go Programming Language Specification

    Appending to and copying slices

    The variadic function append appends zero or more values x to s of type S, which must be a slice type, and returns the resulting slice, also of type S.

    Pointer types

    The value of an uninitialized pointer is nil.

    Selectors

    The following rules apply to selectors:

    4) If x is of pointer type and has the value nil and x.f denotes a struct field, assigning to or evaluating x.f causes a run-time panic.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示