dongyun234854 2017-05-17 21:40 采纳率: 0%
浏览 24
已采纳

GO中的赋值问题

I'm trying to understand why I'm getting the error: invalid memory address or nil pointer dereference

Let's say I have this code (this is not the real one but similar):

type (

    Cat struct {
        Name string 
    }

    Dog struct {
        Name string 
    }

    Pets struct{
        c *Cat
        d *Dog
    }
)

func (c *Cat) Rename(d Dog) string {
     err := SomeErrorChecks()
     name := strings.TrimSpace(d.Name)
     c.Name = name // In this line is where I get the error

     return err         
}

func (p *Pets) SomeFunction() string{
    p.d = &Dog{} 
    p.c = &Cat{}

    p.d.Name = " Foo "

    err := p.c.Rename(*p.d)

    return err
}

func main(){
    //some code

    err := SomeFunction()

    //some error handling not relevant
}

I've checked that strings.TrimSpace(d.Name) returns de desired string. And I've checked that the type of c.Name is string. So, why I can't assing name to c.Name if both are the same type?

  • 写回答

2条回答 默认 最新

  • duanbi1983 2017-05-17 22:15
    关注

    As @JimB already pointed out in his comment

    You are calling Rename with a nil receiver

    which means that, since you're getting the error at c.Name = name, the c receiver inside the Rename method is nil. You need to make sure to initialize c before calling Rename.

    Example

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

报告相同问题?

悬赏问题

  • ¥15 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!