Closure func example in golang

package main

import (
“fmt”
)

type test struct {
name string
fn func() string
}

var d = []test{{
“Google”,
func() string {
str := read()
return str
}}}

func read() string {

str := "golang"

return str

}

func main() {

for i := 0; i < len(d); i++ {

	name := d[i].name

	lang := d[i].fn

	fmt.Println(name, lang)
}

}

Please can tell me i didnt get out of the lang for me :-
OutPut: -
Google 0x483280
realOutPut:-:
Google golang i need

Call the function, don’t just print it:

fmt.Println(name, lang())

https://play.golang.com/p/PrdJ6FBMEyz

1 Like

Thank you,

1 Like

In your struct, fn is just a func() which returns a string, so what you did is

var fn = func() string{return "google"}
print(fn)

So the answer is

var fn = func() string{return "google"}
var s = fn()
print(s)
1 Like

Thank you

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