0

The following compilation error makes sense to me

type A int

var bar int
var foo A
bar = 2
foo = bar // cannot use bar (variable of type int) as type A in assignment

, however the following lack of compilation error surprises me

type A func()

var bar func()
var foo A
bar = func() {}
foo = bar

Similarly, here is an example to define and use a type

type A struct{x int}

bar := A{x: 3}

In the same logic I was hoping to define and use a func type with

type A func(a int) string

bar := A{
    fmt.Println(a)
    return "Hello"
}

but it does not work. One must do

type A func(a int) string

bar := func(a int) string {
    fmt.Println(a)
    return "Hello"
}

It feels to me that a func type is a special kind of type. Is it? Wouldn't iot be more correct/intuitive if golang had a type and a typefunc keywords, such that

type A func()      // would throw a compilation error: a func is not a type
typefunc A func()  // would work fine
Remi.b
  • 17,389
  • 28
  • 87
  • 168
  • 3
    *the following lack of compilation error surprises me [...]* See https://go.dev/ref/spec#Assignability. The compiler allows you to assign `bar` to `foo` because `A` and `func ()` have identical underlying types (`func ()`) and one of them is not a named type. – jub0bs Mar 29 '22 at 10:02
  • 1
    *I was hoping to define and use a func type [...]* Where would the parameter name (`a`) come from? – jub0bs Mar 29 '22 at 10:04
  • @jub0bs For your second comment. As the parameter is made explicit in the type definition, I would have hoped it was not necessary to specify it again when defining the function. `type A func(a int) string`, `bar := A{...}` and `myString := bar(myInt)`. – Remi.b Mar 29 '22 at 10:06
  • 1
    That could work, but I think that would be too much magic for Gophers :) – jub0bs Mar 29 '22 at 10:10

0 Answers0