英文:
Dereferencing pointers in Go
问题
我对为什么第15行无效感到困惑。为什么不能解引用指向big.Int的指针,而可以解引用指向int的指针?
package main
import (
"fmt"
"big"
)
func main() {
var c *int = getPtr()
fmt.Println(c)
fmt.Println(*c)
var d *big.Int = big.NewInt(int64(0))
fmt.Println(d)
// 不会编译 - 隐式赋值给big.Int
// 函数参数中的字段 'neg'
//fmt.Println(*d)
}
func getPtr() *int {
var a int = 0
var b *int = &a
return b
}
英文:
I'm confused as to why line 15 is not valid. Why can't a pointer to a big.Int be dereferenced, whilst a pointer to an int can?
<pre><code>package main
import (
"fmt"
"big"
)
func main() {
var c *int = getPtr()
fmt.Println(c)
fmt.Println(*c)
var d *big.Int = big.NewInt(int64(0))
fmt.Println(d)
// does not compile - implicit assignment of big.Int
// field 'neg' in function argument
//fmt.Println(*d)
}
func getPtr() *int {
var a int = 0
var b *int = &a
return b
}</code></pre>
答案1
得分: 5
这是因为Int是一个具有未导出字段的结构体。当你将一个结构体按值传递给一个函数时,你正在创建它的副本。Go规范指出,为了使这个过程合法,
> ...要么T的所有字段都必须是导出的,要么赋值必须在声明T的同一个包中进行。换句话说,只有当结构体的每个字段都可以被程序单独合法地赋值时,才能将结构体值赋给结构体变量。
英文:
It's because Int is a struct with unexported fields. When you pass a struct by value to a function, you're making a copy of it. The Go spec states that for this to be legal
> ...either all fields of T must be
> exported, or the assignment must be in
> the same package in which T is
> declared. In other words, a struct
> value can be assigned to a struct
> variable only if every field of the
> struct may be legally assigned
> individually by the program.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论