golang new 函数的使用

栏目: Go · 发布时间: 7年前

内容简介:今天看到一道题,先来看看题目问这个为什么会 panic?其实很简单,从报错内容可以看出是空指针引用,所以问题出在这里

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

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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

Hit Refresh

Hit Refresh

Satya Nadella、Greg Shaw / HarperBusiness / 2017-9-26 / USD 20.37

Hit Refresh is about individual change, about the transformation happening inside of Microsoft and the technology that will soon impact all of our lives—the arrival of the most exciting and disruptive......一起来看看 《Hit Refresh》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具