运算符=和:=在Golang的结构中

运算符=和:=在Golang的结构中,go,colon-equals,Go,Colon Equals,为什么这样不行?它与:=运算符一起工作,但为什么我们不能在这里使用=运算符 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

为什么这样不行?它与:=运算符一起工作,但为什么我们不能在这里使用=运算符

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)
}

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

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语言中混淆=和:=。 1. =为先前定义的变量赋值。 2.另一方面,:=同时声明和初始化变量

此外,@Burdy还提供了一个简单的例子来说明=:=


希望这个答案能帮助你澄清你的疑问/困惑

:=运算符在一条指令中声明并初始化变量可能重复的