在 golang 中取消对地址的引用为何会导致“无效的解引用”错误?
时间:2024-03-12
浏览:303
作者:佚名
在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《在 golang 中取消对地址的引用为何会导致“无效的解引用”错误?》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!
type person struct{
Name string
Age int
}
// parameters : (pointer to person struct), which is basically address of person object
func printPerson(p *person) {
// when we add '*' to a address, then it becomes dereferencing, Hence
// I read "*p.Name" as "person object dot Name" and i expect it to give value,
// I get this error:
// ./prog.go:20:15: invalid indirect of p.Name (type string)
// ./prog.go:20:24: invalid indirect of p.Age (type int)
fmt.Println(*p.Name, *p.Age) // does not works, ERROR THROWN
// But this works perfectly
// I read it as "person address dot name and person address dot age"
// for me it does not make sense when we say "address dot field name",
// shouldn't it be "object dot field name ? "
fmt.Println(p.Name, p.Age)
}
func main() {
p := person{"foobar", 23}
printPerson(&p) // we are sending address to the method
}
为什么我们不能执行解引用的对象点字段名称而不是地址点字段名称?请阅读代码注释以获取问题解释,我在这里缺少什么?
解决方案
p.name 和 p.age 按原样工作,因为如果 p 是指向结构的指针,则 p.name 是 (*p).name 的简写。引用自Spec: Selectors:
在表达式 x.f [...] 中,如果 x 的类型是已定义的指针类型,并且 (*x).f 是表示字段(但不是方法)的有效选择器表达式,则 x.f是 (*x).f 的简写。
有鉴于此,*p.name 不会尝试取消引用 p 并引用 name 字段,它会尝试取消引用不是指针的 p.name 字段。
如果您使用括号对间接进行分组,则有效:
fmt.println((*p).name, (*p).age)
但是,由于这种形式非常常见,规范允许您省略指针间接寻址,只需编写 p.name。
在 go 中,& 运算符用作指向变量的指针,并且将其地址保存在内存中。 * 可用于“取消引用”此类指针。取消引用指针使我们可以访问指针指向的值。
在您的示例中,当您的函数接收参数 &p (指向变量 p 的指针)时,您可以直接更改其值,因为结构“person”的成员 name 和 age 不是指针(*t)。
如果您要将结构 person 的成员更改为指针类型(如下例所示),它将打印到控制台:指针值(内存地址)以及 var foobar 和 age 的值指向。
type person struct {
Name *string // Pointer of type string
Age *int // Pointer of type int
}
func printPerson(p *person) {
fmt.Println(p.Name, p.Age) // Pointer values (the memory addresses)
fmt.Println(*p.Name, *p.Age) // Dereferenced values (foobar, 23)
}
func main() {
name := "foobar"
age := 23
p := person{&name, &age}
printPerson(&p)
}本篇关于《在 golang 中取消对地址的引用为何会导致“无效的解引用”错误?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
