Jun 22, 2018

[Go] define interface type during variable declaration :-)

declare interface on the fly
package main

import (
 "fmt"
)

type Fun struct{
 a int
}

func (f Fun) run() int{
 return 42
}


type Run interface{
 run() int
}

func main() {
 var r interface{ run() int} = Fun{42}
 fmt.Println(r.run())
}
declare struct on the fly
package main

import (
 "fmt"
)

type Fun struct{
 a int
}

func (f Fun) run() int{
 return 42
}


type Run interface{
 run() int
}

func main() {
 var r struct{a int} = Fun{42}
 fmt.Println(r.a)
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.