16

golang的匿名struct

 4 years ago
source link: https://studygolang.com/articles/25661
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

go语言匿名struct的用例。

  1. 基本用例
package main
  
import "fmt"

func main() {
    v := struct {
        A int
        B string
    } {
        A: 10,
        B: "bb",
    }
        
    fmt.Printf("%+v\n", v)
}

或者

package main
  
import "fmt"

func main() {
    v := struct {
        A int
        B string
    } { 10, "bb"}
        
    fmt.Printf("%+v\n", v)
}
  1. 包含slice
package main
  
import "fmt"

func main() {
    v := struct {
        A int
        B string
        C []int
    } { 10, "bb", []int {1,2,3}}
        
    fmt.Printf("%+v\n", v)
}
  1. 嵌套匿名struct
package main
  
import "fmt"

func main() {
    v := struct {
        A int
        B string
        C struct {
            C1 int
            C2 string
        }
    } {
        10,
        "bb",
        struct {C1 int
                C2 string} {
                    100,
                    "ccc"},
    }
        
    fmt.Printf("%+v\n", v)
}

这个地方需要注意的是在定义嵌套内对象的时候又有一遍类型的声明,感觉是重复的,显得代码不是很简洁,这没有办法go语言就这么设计的槽点,就像第二个例子的slice一样也是声明了两遍。

其实希望的这种语句格式:

1  package main
     2    
     3  import "fmt"
     4  
     5  func main() {
     6      v := struct {
     7          A int
     8          B string
     9          C struct {
    10              C1 int
    11              C2 string
    12          }
    13      } {
    14          10,
    15          "bb",
    16          {100, "ccc"},
    17      }
    18          
    19      fmt.Printf("%+v\n", v)
    20  }

遗憾的是编译器不接受这种格式:

$ go build test.go
# command-line-arguments
./test.go:16:9: missing type in composite literal

感觉编译器应该完全能支持这种格式,从语法分析上说,这种写法没有问题,而且不会产生二义,不知道golang出于什么原因不支持,很奇怪的说。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK