Expanding anonymous functions in another function

package main

import "fmt"

func main(){
        fmt.Println(func(){fmt.Println("hello world");}());

I expected to see

hello world

but got the following error instead

# command-line-arguments
./5.go:6: (func literal)() used as value

Why did it not print “hello world” ??

Your anonymous function does not return anything. Try this:

package main

import "fmt"

func main() {
	fmt.Println(func() string { return "hello world" }())


1 Like

I have the impression that you have changed your question. Now it is very different to how it was when I answered it. Please don’t do that.

Your question as it currently is makes no sense. What do you expect? fmt.Println can’t tak a func as only parameter.

Yes, I changed it, I thought I improved it, but don’t understand how it’s more worse…

Earlier it was

fmt.Println(func(){return "hello world";}());

Now, it’s as you see above in the question.

Why does the current line in question not make any sense?

fmt.Println has this sigtnature:

func Println(a ...interface{}) (n int, err error)

This means that it can accept any number of parameters that implement any interface. A func can not be used here.

I have yet to read about interface, but as I understand, according to this statement, is return statement an interface itself??

May I suggest that you work throug the Tour of Go? It is a great way to learn the basics of Go.

1 Like

Thanks, would start reading that, but just one question before we leave the conversation, is return keyword an interface?

No, return is a statement. You can read all the details about in in the spec: https://golang.org/ref/spec#Return_statements

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