我一直在关注 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/