如何为指针参数分配地址

时间:2019-03-15 05:18:27

标签: pointers go

我正在尝试编写一个带有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
}

1 个答案:

答案 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}