这两个结构定义有什么区别?

huangapple go评论80阅读模式
英文:

What is the difference between these 2 struct definitions?

问题

这两个结构类型定义有什么区别?

var query1 struct {
    A, B string
}

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

为什么我不能像第二个结构体那样给第一个结构体初始化赋值?它们之间有什么区别?

英文:

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?

答案1

得分: 4

你可以"用第二种方式初始化第一种结构体"。例如,

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

输出结果为:

{Hello 5} {Hello 5}

query1 是一个变量声明query2 是一个短变量声明

英文:

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.

huangapple
  • 本文由 发表于 2014年8月17日 23:18:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/25350553.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定