I'm trying to write a function that takes in a struct
pointer and points it to another address.
I know I can simply write a function that takes a pointer and manipulates struct
fields like so:
func ManipulateStruct(myPointer *MyStruct) {
myPointer.Field1 = "new value"
myPointer.Field2 = 10
}
However, is it possible to write something like:
func ManipulateStruct(myPointer *MyStruct) {
newPointer := new(MyStruct)
newPointer.Field1 = "new value"
newPointer.Field2 = 10
// myPointer = &newPointer <-- illegal
// cannot use &newPointer (type **MyStruct) as type *MyStruct in assignment
myPointer = newPointer
}
Using new
makes a pointer to your struct
so you need pointer like this:
package main
import "fmt"
func main() {
var ptr *MyStruct
ManipulateStruct(&ptr)
fmt.Println(ptr)
}
func ManipulateStruct(myPointer **MyStruct) {
newPointer := new(MyStruct)
newPointer.Field1 = "new value"
newPointer.Field2 = 10
*myPointer = newPointer
}
type MyStruct struct {
Field1 string
Field2 int
}
Output:
&{new value 10}