I'm a bit new to Go (Golang) and am getting a bit confused by pointers. In particular, I can't seem to figure out how to resolve or dereference a pointer.
The following is an example:
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
In the example above, is it possible to call "bFunc" with "structInstance"?
This could potentially be even more of an issue if the "someStruct" struct is in another package and since it's unexported, the only way to get an instance of it will be through some "New" function (which, let's say will all return pointers).
Thanks.
You're confusing 2 issues here, this has nothing to do with pointers, it has to do with exported variables.
type someStruct struct {
propertyOne int
propertyTwo map[string]interface{}
}
someStruct
, propertyOne
and propertyTwo
aren't exported (they don't start with a capital letter), so even if you use NewSomeStruct
from another package, you wouldn't be able to access the fields.
And about bFunc
, you dereference a pointer by appending *
before the variable name, for example:
bFunc(*structInstance)
I highly recommend going through Effective Go, specially the Pointers vs. Values section.