我正在尝试编写一个函数,该函数接受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
}

最佳答案

使用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}

关于pointers - 如何为指针参数分配地址,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55175988/

10-11 05:57