golang new 函数的使用

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

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 看起来更简洁。

GO语言学习交流群:148745800

发布了20 篇原创文章 · 获赞 258 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/lingshengxueyuan/article/details/103142656
今日推荐