英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论