Search code examples
gocolon-equals

operator = and := in struct in Golang


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

Solution

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