Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function to return an Interface

Tags:

How come I can say that the result of CreateLion(), a pointer to a struct that implements the Cat interface, is an instance of the Cat interface, and yet I cannot say that CreateLion() is of type "function that returns the Cat interface."

What is the standard Golang approach to achieving this type of behavior?

package main

import "fmt"

func main() {
    var lion Cat := CreateLion()
    lion.Meow()

    // this line breaks. Why?
    var cf CatFactory = CreateLion
}

type Cat interface {
    Meow()
}

type Lion struct {}
func (l Lion) Meow() {
    fmt.Println("Roar")
}

// define a functor that returns a Cat interface
type CatFactory func() Cat

// define a function that returns a pointer to a Lion struct
func CreateLion() *Lion {
    return &Lion{}
}
like image 274
zian Avatar asked Jan 26 '16 03:01

zian


People also ask

Can a function return an interface?

Pedantically, but crucially, it does not return an interface. It returns an object reference.

What is the return type of interface?

If an interface is defined to be the return type of a method then instances of classes derived from that interface can be returned. The benefit of doing that is no different from returning objects of classes derived from a class.

Can we return an interface in C#?

Yes, you can return an interface.


1 Answers

Try this:

package main

import "fmt"

type Cat interface {
    Meow()
}

type Lion struct{}

func (l Lion) Meow() {
    fmt.Println("Roar")
}

type CatFactory func() Cat

func CreateLion() Cat {
    return Lion{}
}

func main() {
    lion := CreateLion()
    lion.Meow()

    var cf CatFactory = CreateLion
    fLion := cf()
    fLion.Meow()
}

In most cases, you can assign any type to base type interface{}. But situation changes if type of function parameter is a map[T]interface{}, []interface{} or func() interface{}. In this case the type must be the same.

like image 149
Oleksiy Chechel Avatar answered Oct 06 '22 23:10

Oleksiy Chechel