我对 Go (Golang) 有点陌生,并且对指针有点困惑。特别是,我似乎无法弄清楚如何解析或取消引用指针。下面是一个例子:package mainimport "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”函数(假设所有函数都返回指针) )。
1 回答
慕盖茨4494581
TA贡献1850条经验 获得超11个赞
你在这里混淆了两个问题,这与指针无关,它与导出的变量有关。
type someStruct struct {
propertyOne int
propertyTwo map[string]interface{}
}
someStruct,propertyOne并且propertyTwo不会导出(它们不以大写字母开头),因此即使您NewSomeStruct从另一个包中使用,您也无法访问这些字段。
而 about bFunc,您可以通过*在变量名之前附加来取消引用指针,例如:
bFunc(*structInstance)
我强烈建议您阅读Effective Go,特别是Pointers vs. Values部分。
- 1 回答
- 0 关注
- 194 浏览
添加回答
举报
0/150
提交
取消