解决指针

时间:2014-08-13 00:11:34

标签: 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))
}

Code on" Go Playground"

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

在上面的示例中,是否可以调用" bFunc"使用" structInstance"?

如果" someStruct"这可能更成为一个问题。 struct在另一个包中,并且由于它未被导出,获取它的实例的唯一方法是通过一些" New"函数(让我们说它们都会返回指针)。

感谢。

1 个答案:

答案 0 :(得分:3)

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

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

someStructpropertyOnepropertyTwo未导出(它们不以大写字母开头),因此即使您使用NewSomeStruct从另一个包中,您将无法访问这些字段。

关于bFunc,您可以通过在example的变量名之前附加*来取消引用指针:

bFunc(*structInstance)

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