gpt4 book ai didi

go - 运算符 = 和 := in struct in Golang

转载 作者:数据小太阳 更新时间:2023-10-29 03:43:55 26 4
gpt4 key购买 nike

为什么这行不通?它适用于 := 运算符,但为什么我们不能在这里使用 = 运算符?

package main

import "fmt"

type Vertex struct {
X, Y int
}


func main() {
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
fmt.Println(v1, p, v2, v3)
}

最佳答案

您可以通过多种方式创建新的 Vertex 类型的实例:

1: var c Circle 您可以使用 . 运算符访问字段:

package main

import "fmt"

type Vertex struct {
X, Y int
}
func main() {
var f Vertex
f.X = 1
f.Y = 2
fmt.Println(f) // should be {1, 2}
}

2:使用:=运算符

package main

import "fmt"

type Vertex struct {
X, Y int
}
func main() {
f := Vertex{1, 2}
fmt.Println(f) // should be {1, 2}
}

关于go - 运算符 = 和 := in struct in Golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45252693/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com