Function type error: "invalid type for composite literal:"

What’s the reason that my defined function type can’t be used in the following expression?

Compiler complains the following code: invalid type for composite literal: myFuncType

type myFuncType func()


func main() {

  funcVar := myFuncType{fmt.Println("hello")}

}

The same user-defined function type is ok for a function parameter type like func1(func2 myFuncType)

You have a few things wrong here that are likely causing you issues.

For starters, you want to use parenthesis when setting funcVar, not { and }. Eg:

funcVar := myFuncType(func() {})

The second, and more important issue, is that you are calling the fmt.Println function and trying to set whatever it returns to the funcVar variable. Looking at the docs for fmt.Println we see that a call to it returns (int, error) (see https://golang.org/pkg/fmt/#Println) so that likely isn’t what you wanted. We also can’t assign the fmt.Println function to any variable of type myFuncType because Println doesn’t match the func() definition. Println accepts arguments and has return values.

What you likely wanted was a closure. Something like:

funcVar := func() { fmt.Println("hello") }

And then you can get the myFuncType out of it by using parenthesis like I said before.

funcVar := myFuncVar(func() { fmt.Println("hello") })

Putting it all together you can see a working version here: https://play.golang.org/p/Z3aI0swpL3

3 Likes

Thanks Jon. I think my original mistake was trying to declare an anonymous func without the keyword “func”(was trying to replace it with myFuncType).

sort like what’s discussed in this thread

english := Greeting {
    return return "Hello, " + name
}

but no, there is no way in Go. The declaration of english can’t use Greeting, and must repeat the function signature.

I see what you mean now.

I can’t speak to exactly why that wasn’t implemented, but if I had to guess I would say that it was likely avoid confusion. Eg if what you linked worked, you could write code like:

type Demo struct {
	F func()
}

type DemoFn func()

func main() {
	d := Demo{
		buildFn("hello"),
	}
	d.F()

	// THIS DOES NOT WORK!!!
	dFn := DemoFn{
		fmt.Println("hello")
	}
}

func buildFn(msg string) func() {
	return func() {
		fmt.Println(msg)
	}
}

Notice that the declaration for Demo and DemoFn are very similar looking. In fact, the only real way to tell the difference between the two is a single comma, and if that were all that distinguished between behavior I could easily see that leading to incredibly frustrating bugs and hard-to-read code.

2 Likes

nice thought. Thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.