operator = and := in struct in Golang

614 Views Asked by At

Why doesn't this work? It works with := operator but why can't we use = operator here?

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

There are 2 best solutions below

0
On BEST ANSWER

You can create an instance of your new Vertex type in a variety of ways:

1: var c Circle You can access fields using the . operator:

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: Using := operator

package main

import "fmt"

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

:= will initialize and declares the variables at the same time. It is for simplicity. Please don't get confuse in = and := in Go Language. 1. = assigns values to previously defined variables. 2. On the other hand, := declares and initialize variables at the same time.

Also, @Burdy gave a simple example of both = and :=.

Hope this answer helps you and clear your doubt/confusion.