Does Go support anonymous methods for structures and if they do how do you create and call them?
This is the code I've been trying to get work but I'm unsure if Go(go version go1.1.2 linux/amd64) supports anonymous methods to structures.
package main
import (
"fmt"
)
type Person struct{
name string
age int
}
func (p Person) get_details() string {
return fmt.Sprintf("Name->%s, Age->%d", p.name, p.age)
}
func main() {
p := Person{name:"G4143", age:5}
//simple anonymous function which works
fmt.Println(func(i int)int{return i * i}(34))
str := p.get_details()
fmt.Println(str)
//anonymous method which won't compile
str = p.func(p Person)()string{return fmt.Sprintf("Name->%s, Age->%d", p.name, p.age) }()
fmt.Println(str)
}
I thank-you for any guidance..
You can't do that, however you have 3 options :
Private method :
type Person struct{
name string
age int
}
func (p Person) Details() string { // public
return fmt.Sprintf("Name->%s, Age->%d", p.name, p.age)
}
func (p Person) details() string { // private, notice the lowercase D
return fmt.Sprintf("Name->%s, Age->%d", p.name, p.age)
}
Use the inline function just like this :
str = func()string{return fmt.Sprintf("Name->%s, Age->%d", p.name, p.age) }()
Pass the variable to the inline function :
str = func(p Person) string { return fmt.Sprintf("Name->%s, Age->%d", p.name, p.age) }(p)
No. As this answer is to short: There is really no way to do this. BTW I cannot see any reason to do this.
No, that's not possible, but more importantly you don't need that because of the closure system : p
is already available in your function, like the other variables of the external scope.
str = func()string{return fmt.Sprintf("Name->%s, Age->%d", p.name, p.age) }()