Go - 实例化结构并获取指向它的指针的 "&MyStruct{1, 2}"语法何时有用?

标签 go struct

我一直在关注 Go 编程语言,以熟悉该语言,该语言的一个功能让我感到好奇。

在关于Struct Literals的步骤中,他们解释说您可以通过多种方式实例化结构:

type Vertex struct {
    X, Y int
}

var (
    v1 = Vertex{1, 2}  // has type Vertex
    v2 = Vertex{X: 1}  // Y:0 is implicit
    v3 = Vertex{}      // X:0 and Y:0
    p  = &Vertex{1, 2} // has type *Vertex
)

我可以毫无疑问地理解前三种方法的工作原理以及它们何时有用,但我无法找出最后一种解决方案的任何用例 p = &Vertex{1, 2} .

事实上,我无法想象在代码中没有可用并使用 Vertex 类型的变量的情况下必须实例化 *Vertex 的情况:

func modifyingVertexes(myVertex *Vertex) {
    myVertex.X = 42;
}

func main() {
    myVertex := Vertex{1, 2}

    modifyingVertexes(&myVertex)

    fmt.Println(myVertex.X)
}

如果可以实现以下功能,我可以看到它的用途:

func modifyingVertexes(myVertex *Vertex) {
    myVertex.X = 42;
}

func main() {
    modifyingVertexes(&Vertex{1, 2})

    fmt.Println(???.X) // Accessing the vertex initialized in the modifyingVertexes func call
}

但既然我认为这是不可能的,我真的不知道它如何使用?

谢谢!

最佳答案

这是一个非常常见的 Go 习惯用法,返回已初始化的 struct 变量的地址。

package main

import "fmt"

type Vertex struct {
    X, Y int
}

func NewVertex(x, y int) *Vertex {
    return &Vertex{X: x, Y: y}
}

func main() {
    v := NewVertex(1, 2)
    fmt.Println(*v)
}

Playground :https://play.golang.org/p/UGOk7TbjC2a

输出:

{1 2}

这也是隐藏未导出(私有(private))struct 字段的非常常见的习惯用法。

package main

import "fmt"

type Vertex struct {
    x, y int
}

func NewVertex(x, y int) *Vertex {
    return &Vertex{x: x, y: y}
}

func (v *Vertex) Clone() *Vertex {
    return &Vertex{x: v.x, y: v.y}
}

func main() {
    v := NewVertex(1, 2)
    fmt.Println(*v)

    w := v.Clone()
    fmt.Println(*w)
}

Playground :https://play.golang.org/p/ScIqOIaYGPn

输出:

{1 2}
{1 2}

在 Go 中,所有参数都是按值传递的。对大型结构使用指针会更有效。如果您希望更改 struct 参数的值,则还需要指针。

关于Go - 实例化结构并获取指向它的指针的 "&MyStruct{1, 2}"语法何时有用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48602020/

相关文章:

go - 如何将文件嵌入到 Go 二进制文件中

go - 在没有 oAuth 的情况下针对 Azure AD 验证用户凭据

c - 静态结构初始化

c - 使用 C 将二进制文件读入结构体,处理 char [8]

c - 如何将二进制文件读入缓冲区,然后在不同点设置结构指针以初始化它们?

encryption - 加密数据的机器学习

go - 后台打印程序概念/API 和 channel : issue passing jobs to a queue from serveHTTP

go - Go 练习之旅 #23 : rot13Reader

c++ - 尝试初始化位于区域结构内的边缘结构。我怎么做?

c++ - 如何在 C++ 中制作可调试文件范围(静态?)类?