On 13 December 2016 at 01:08, go-question <[email protected]> wrote:
>
> I noticed that its possible to define/scope types/interfaces in functions.
>
> Now I'm not arguing that this is good practice, but for the sake of
> curiosity.
> How can I then add a method w/ a receiver to type foo so that it satisfies
> interface ifoo? (in function scope)
>
>
> func main() {
>
> type foo struct{
> a string
> }
>
> type ifoo interface {
> Bar()
> }
>
> // possible?
> foo{"baz"}.Bar()
>
> }
Technically you can do it (you can make a program that will compile,
demonstrating that your type does satisfy the interface)
but it's not very useful because it'll crash when you call the method :-)
package main
func main() {
type ifoo interface {
Bar()
}
type foo struct {
ifoo
a string
}
// Yup, it's possible, but it's probably not what you want.
foo{a: "baz"}.Bar()
}
This is still a useful technique in some circumstances though (for example
if there's a large interface that I want to mock only a small portion of,
I can embed the interface and define only those methods I expect to be called).
Another useful technique when you want function-scoped methods is this:
package main
import "fmt"
type ifoo interface {
Bar()
}
type ifooFuncs struct {
bar func()
// ... and another function-typed field for each method.
}
func (f ifooFuncs) Bar() {
f.bar()
}
func main() {
x := ifooFuncs{
bar: func() {
fmt.Println("bar")
},
}
x.Bar()
}
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.