softshipper
softshipper

Reputation: 34099

What is the difference between these 2 struct definitions?

What is the difference between these two struct type definitions?

var query1 struct {
    A, B string
}

query2 := struct {
    va1 string
    va2 int
}{"Hello", 5}

Why can I not initialize the first with value like second? What is the difference between them?

Upvotes: 0

Views: 95

Answers (1)

peterSO
peterSO

Reputation: 166825

You can "initialize the first with value like second." For example,

package main

import "fmt"

func main() {
    var query1 = struct {
        A, B string
    }{"Hello", "5"}

    query2 := struct {
        va1 string
        va2 int
    }{"Hello", 5}

    fmt.Println(query1, query2)
}

Output:

{Hello 5} {Hello 5}

query1 is a variable declaration. query2 is a short variable declaration.

Upvotes: 4

Related Questions