1

I am learning the go basic grammar. The document says "go doesn’t support the Automatic Type Conversion or Implicit Type Conversion ". I wrote some code to test it.

package main

import (
    "fmt"
)
type myfloat float32

type myfunc func(string)

func bbb(a myfloat) {
    fmt.Printf("bbb %T\n", a)
}

func ccc(m myfunc) {
    fmt.Printf("ccc %T\n", m)
}

func main() {
    i := float32(1.1)
    bbb(i) //can't build

    d := func(s string) {}
    ccc(d)
}

bbb(i) can't build successfully, this is due to the type is different. My question is why ccc(d) can pass build? myfunc is also a user defined type, which is similar like the myfloat.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
shuming
  • 25
  • 6
  • The difference is that `i`'s type is `float32` which is a named type, while `d`'s type is `func(string)` which is an unnamed type, and assignability rules apply in the second case but not in the first case. See the marked duplicate for details. – icza Nov 20 '19 at 08:29
  • Thank you for your explanation! @icza I just checked the Go Spec, there is a little update on the second rule. _**x's type V and T have identical underlying types and at least one of V or T is not a defined type.**_ I am more confused. 1. float32 and myfloat have the identical underlying type. 2. float32 is not a defined type. Why can't assign i to myfloat? – shuming Nov 21 '19 at 03:31
  • You wrote: _"float32 is not a defined type"_. This is not true, `float32` is a predefined type. So your quoted part from assignability rules don't apply, that's why you can't assign `i` (of type `float32`) to a variable of type `myfloat` (also a named, defined type). – icza Nov 21 '19 at 16:31
  • Thank you! named / unamed, defined / non-defined type are not easy to understand for new comers :( This article explains this concept clearly. Post here for others [link] https://go101.org/article/type-system-overview.html – shuming Nov 25 '19 at 01:47

0 Answers0