我对 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))
}
“去游乐场”上的代码
http://play.golang.org/p/FlTh7_cuUb
在上面的例子中,是否可以用“structInstance”调用“bFunc”?
如果“someStruct”结构在另一个包中并且由于它未导出,则这可能是一个更大的问题,因此获取它的实例的唯一方法将是通过一些“New”函数(假设所有函数都返回指针) )。
慕盖茨4494581
相关分类