为什么结构体与其他类型的“实例化”方式不同?

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

Go: Why are structs "instantiated" differently from other types?

问题

在Go语言中,结构体的实例化与“常规”类型有所不同:

如果是常规类型:MyFloat(2)

如果是结构体:MyFloat{2}

这样设计的原因是什么?

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type MyFloat float64
  6. type MyFloat2 struct {
  7. X float64
  8. }
  9. func main() {
  10. f1 := MyFloat(2)
  11. f2 := MyFloat2{3}
  12. fmt.Println(f1)
  13. fmt.Println(f2)
  14. }
英文:

In golang, structs are instantiated differently from "regular" types:

If it's a regular type: MyFloat(2)

If it's a struct: MyFloat{2}

Is there a particular reason for this?

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type MyFloat float64
  6. type MyFloat2 struct {
  7. X float64
  8. }
  9. func main() {
  10. f1 := MyFloat(2)
  11. f2 := MyFloat2{3}
  12. fmt.Println(f1)
  13. fmt.Println(f2)
  14. }

答案1

得分: 3

MyFloat(2) 是一个类型转换MyFloat2{3} 是一个复合字面量

类型转换可以用于结构体:

  1. var f3 struct {
  2. X float64
  3. }
  4. f4 := MyFloat2(f3)

playground

英文:

MyFloat(2) is a conversion. MyFloat2{3} is a composite literal.

Conversions can be used on structs:

  1. var f3 struct {
  2. X float64
  3. }
  4. f4 := MyFloat2(f3)

playground

huangapple
  • 本文由 发表于 2014年10月22日 06:26:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/26497428.html
匿名

发表评论

匿名网友

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

确定