在Go语言中解引用指针

huangapple go评论92阅读模式
英文:

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 &#39;neg&#39; 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.

huangapple
  • 本文由 发表于 2010年3月6日 02:06:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/2388909.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定