Go语言中的两种结构声明形式

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

Two forms of struct declaration in Go

问题

我在函数范围内有两种结构声明的形式。就我所看到的,下面列出的代码片段运行得很好。问题是这两种声明方式之间有什么区别?这只是一个语义问题,还是在底层有一些巧妙的东西?

package main

import "fmt"

func main() {
    type Person1 struct {
        Name string
        Id int
    }
    person1 := &Person1{Name : "John Smith", Id : 10}
    fmt.Printf("(%s, %d)\n", person1.Name, person1.Id)
    var person2 struct {
        name string
        id int
    }
    person2.name = "Kenneth Box"
    person2.id = 20
    fmt.Printf("(%s, %d)\n", person2.name, person2.id)
}
英文:

I've got two forms of struct declaration in the function scope. As far as I could see the bellow-listed snippet woks just fine. The question is what's the difference between the two declaration ways? Is that only a semantic question or there is something tricky under the covers?

package main

import "fmt"

func main() {
    type Person1 struct {
        Name string
        Id int
    }
    person1 := &Person1{Name : "John Smith", Id : 10}
    fmt.Printf("(%s, %d)\n", person1.Name, person1.Id)
    var person2 struct {
        name string
        id int
    }
    person2.name = "Kenneth Box"
    person2.id = 20
    fmt.Printf("(%s, %d)\n", person2.name, person2.id)
}

答案1

得分: 3

一个是有名字的类型 - 如果需要的话,可以使用类型名称创建多个变量。

另一种类型没有名字。除了使用:=运算符之外,您无法创建更多的该类型变量。

英文:

One is a named type - you can create multiple variables of that type, if you need to, using the type name.

The other type has no name. You cannot create more variables of the type other than by using the := operator.

答案2

得分: 2

person1是一个指向结构体的指针,而person2是一个结构体的值本身。如果你这样做了person1 := Person1{Name : "John Smith", Id : 10},那么它们是相同的。

英文:

person1 is a pointer to a struct, while person2 is a struct value itself. If you had done person1 := Person1{Name : "John Smith", Id : 10} then it would be the same

huangapple
  • 本文由 发表于 2010年9月27日 21:44:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/3804389.html
匿名

发表评论

匿名网友

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

确定