golang new 函数的使用

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

内容简介:今天看到一道题,先来看看题目问这个为什么会 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 看起来更简洁。


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

查看所有标签

猜你喜欢:

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

Java Message Service API Tutorial and Reference

Java Message Service API Tutorial and Reference

Hapner, Mark; Burridge, Rich; Sharma, Rahul / 2002-2 / $ 56.49

Java Message Service (JMS) represents a powerful solution for communicating between Java enterprise applications, software components, and legacy systems. In this authoritative tutorial and comprehens......一起来看看 《Java Message Service API Tutorial and Reference》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具