美文网首页
golang new 函数的使用

golang new 函数的使用

作者: Yt_cc | 来源:发表于2019-11-19 15:54 被阅读0次

今天看到一道题,先来看看题目

type Point struct {

         X, Y float64

}

func (p *Point) Abs() float64{

        return math.Sqrt(p.X*p.X + p.Y*p.Y)

}

func main() {

          var p *Point

        fmt.Println(p.Abs())

}

问这个为什么会 panic?

panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0xffffffff addr=0x0 pc=0xd2c5a]

goroutine 1 [running]:

main.(*Point).Abs(...)

          ../main.go:6 

main.main()

          ../main.go:11 +0x1a

其实很简单,从报错内容可以看出是空指针引用,所以问题出在这里

// 这种声明方式 p 是一个 nil 值

var p *Point

// 改为

var p *Point = new(Point)

// 或者

var p *Point = &Point{}

为什么这么改就可以呢,我们看看定义,大致意思是,new函数会分配内存,返回的值是一个指向该类型零值的地址。

// The new built-in function allocates memory. The first argument is a type,

// not a value, and the value returned is a pointer to a newly

// allocated zero value of that type.

func new(Type) *Type

当然除了用 new ,普通的方法也行。但是 new 看起来更简洁。

相关文章

网友评论

      本文标题:golang new 函数的使用

      本文链接:https://www.haomeiwen.com/subject/ndawictx.html