Reputation: 1323
When I assign a function to variable and try to invoke it . It throws an error 'too many arguments to return'
package main
import "fmt"
func main() {
first_name := "Hello"
last_name := "World!"
full_name := func() {
return first_name
}
fmt.Println(first_name)
fmt.Println(last_name)
fmt.Println(full_name)
}
Upvotes: 2
Views: 5322
Reputation: 297
You need to change your function definition to the following:
full_name := func() string {
return first_name
}
That's how you tell Go that you intend to return something from a function and what that something is (a string in this case).
Then later you should call your newly created function like this:
fmt.Println(full_name())
Upvotes: 5
Reputation: 9881
You didn't declare your function correctly.
full_name := func() string{ // add a return type
return first_name
}
Even for an anonymous function, arguments and return values must be declared. Since you did not specify any return value, you cannot use return xx
.
Also, be aware that fmt.Println(full_name)
will return the address of the function, not execute the function. Try fmt.Println(full_name())
instead.
Upvotes: 1