pointers - 解析指针

标签 pointers go

我对 Go (Golang) 有点陌生,并且对指针有点困惑。特别是,我似乎无法弄清楚如何解析或取消引用指针。

以下是一个示例:

package main

import "fmt"

type someStruct struct {
    propertyOne int
    propertyTwo map[string]interface{}
}

func NewSomeStruct() *someStruct {
    return &someStruct{
        propertyOne: 41,
    }
}

func aFunc(aStruct *someStruct) {
    aStruct.propertyOne = 987
}

func bFunc(aStructAsValue someStruct) {
    // I want to make sure that I do not change the struct passed into this function.
    aStructAsValue.propertyOne = 654
}

func main() {
    structInstance := NewSomeStruct()
    fmt.Println("My Struct:", structInstance)

    structInstance.propertyOne = 123 // I will NOT be able to do this if the struct was in another package.
    fmt.Println("Changed Struct:", structInstance)

    fmt.Println("Before aFunc:", structInstance)
    aFunc(structInstance)
    fmt.Println("After aFunc:", structInstance)

    // How can I resolve/dereference "structInstance" (type *someStruct) into
    // something of (type someStruct) so that I can pass it into bFunc?

    // &structInstance produces (type **someStruct)

    // Perhaps I'm using type assertion incorrectly?
    //bFunc(structInstance.(someStruct))
}

“Go Playground”代码

http://play.golang.org/p/FlTh7_cuUb

在上面的例子中,是否可以用“structInstance”调用“bFunc”?

如果“someStruct”结构位于另一个包中,并且由于它未导出,那么获取它的实例的唯一方法将是通过一些"new"函数(假设该函数将所有返回指针)。

谢谢。

最佳答案

您在这里混淆了两个问题,这与指针无关,它与导出的变量有关。

type someStruct struct {
    propertyOne int
    propertyTwo map[string]interface{}
}

someStructpropertyOnepropertyTwo 不会导出(它们不以大写字母开头),所以即使您使用NewSomeStruct 来自另一个包,您将无法访问这些字段。

对于bFunc,您可以通过在变量名称前附加*来取消引用指针,例如example :

bFunc(*structInstance)

我强烈建议浏览Effective Go ,特别是 Pointers vs. Values部分。

关于pointers - 解析指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25276100/

相关文章:

c - 提供特定值但返回错误指针

C++函数指针和成员函数指针

go - 为什么 Go 需要这么多 CPU 来构建一个包?

go - Go 编译文件如何在不同的操作系统或 CPU 架构上工作?

Go http 监听器,每秒更新一次数据

go - 读取 revel app.conf 中的环境变量

objective-c - 你能帮我理解指针吗?

pointers - func 列表中的 Golang funcs 取最后一个值

mysql - golang 编辑先前设置的标志。 MySQL错误1045

c - 将指向结构的指针作为参数有什么意义?