我对 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{}
}
someStruct
、propertyOne
和 propertyTwo
不会导出(它们不以大写字母开头),所以即使您使用NewSomeStruct
来自另一个包,您将无法访问这些字段。
对于bFunc
,您可以通过在变量名称前附加*
来取消引用指针,例如example :
bFunc(*structInstance)
我强烈建议浏览Effective Go ,特别是 Pointers vs. Values部分。
关于pointers - 解析指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25276100/