我正在尝试编写一个带有struct
指针并将其指向另一个地址的函数。
我知道我可以简单地编写一个带有指针并按如下方式操纵struct
字段的函数:
func ManipulateStruct(myPointer *MyStruct) {
myPointer.Field1 = "new value"
myPointer.Field2 = 10
}
但是,是否可以写类似这样的东西:
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
}
答案 0 :(得分:3)
使用new
会指向您的struct
指针,因此您需要像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
}
输出:
&{new value 10}