struct_conversions.go 534 B

12345678910111213141516171819202122232425
  1. // struct_conversions.go
  2. package main
  3. import (
  4. "fmt"
  5. )
  6. type number struct {
  7. f float32
  8. }
  9. type nr number // alias type
  10. func main() {
  11. a := number{5.0}
  12. b := nr{5.0}
  13. // var i float32 = b // compile-error: cannot use b (type nr) as type float32 in assignment
  14. // var i = float32(b) // compile-error: cannot convert b (type nr) to type float32
  15. // var c number = b // compile-error: cannot use b (type nr) as type number in assignment
  16. // needs a conversion:
  17. var c = number(b)
  18. fmt.Println(a, b, c)
  19. }
  20. // output: {5} {5} {5}