Go结构中的无名字段?

wljmcqd8  于 2023-09-28  发布在  Go
关注(0)|答案(3)|浏览(118)
  1. package main
  2. import "fmt"
  3. type myType struct {
  4. string
  5. }
  6. func main() {
  7. obj := myType{"Hello World"}
  8. fmt.Println(obj)
  9. }

结构中的无名字段有什么用途?
是否可以像访问命名字段那样访问这些字段?

xuo3flqw

xuo3flqw1#

没有不尊重选择的答案,但它没有澄清我的概念。
有两件事正在发生。首先是匿名字段。二是“提升”领域。
对于匿名字段,可以使用的字段名是类型的名称。第一个匿名字段是“提升的”,这意味着您在结构上访问的任何字段都“传递”到提升的匿名字段。这显示了两个概念:

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. type Widget struct {
  7. name string
  8. }
  9. type WrappedWidget struct {
  10. Widget // this is the promoted field
  11. time.Time // this is another anonymous field that has a runtime name of Time
  12. price int64 // normal field
  13. }
  14. func main() {
  15. widget := Widget{"my widget"}
  16. wrappedWidget := WrappedWidget{widget, time.Now(), 1234}
  17. fmt.Printf("Widget named %s, created at %s, has price %d\n",
  18. wrappedWidget.name, // name is passed on to the wrapped Widget since it's
  19. // the promoted field
  20. wrappedWidget.Time, // We access the anonymous time.Time as Time
  21. wrappedWidget.price)
  22. fmt.Printf("Widget named %s, created at %s, has price %d\n",
  23. wrappedWidget.Widget.name, // We can also access the Widget directly
  24. // via Widget
  25. wrappedWidget.Time,
  26. wrappedWidget.price)
  27. }

输出为:

  1. Widget named my widget, created at 2009-11-10 23:00:00 +0000 UTC m=+0.000000001, has price 1234
  2. Widget named my widget, created at 2009-11-10 23:00:00 +0000 UTC m=+0.000000001, has price 1234```
展开查看全部
63lcw9qa

63lcw9qa2#

参见“Embedding in Go”:在结构体中嵌入匿名字段:这通常用于嵌入式结构,而不是string等基本类型。该类型没有要公开的“提升字段”。
如果x.f是表示字段或方法f的法律的选择器,则结构x中匿名字段的字段或方法f被称为promoted
提升字段的作用类似于结构的普通字段,只是它们不能用作结构的复合文本中的字段名称。
(here string本身没有字段)
请参见“Embeddding when to use pointer”中的类型嵌入示例。
是否可以像访问命名字段那样访问这些字段?
fmt.Println(obj.string)将返回Hello World而不是{Hello World}

gj3fmq9x

gj3fmq9x3#

匿名字段是没有名字的字段。您可以通过以下类型访问它:

  1. type myType struct {
  2. string
  3. }
  4. func main() {
  5. obj := myType{"Hello World"}
  6. fmt.Println(obj.string)
  7. }

当一个 anonymous field 是一个结构体并且有自己的字段时,这些字段被 * 提升 * 为可访问的,就好像它们是父结构体的直接字段一样(除非父结构体已经有一个具有该名称的字段):

  1. type myType struct {
  2. string
  3. j int
  4. }
  5. type myParentType struct {
  6. myType
  7. i int
  8. }
  9. func main() {
  10. o := myType{"Hello World", 0}
  11. obj := myParentType{o, 1}
  12. fmt.Println(obj.j) // 0
  13. fmt.Println(obj.myType.j) // 0, also works
  14. fmt.Println(obj.i) // 1
  15. }
展开查看全部

相关问题