function to return an Interface

前端 未结 4 665
名媛妹妹
名媛妹妹 2021-02-07 08:27

The code below is really self-explanatory.

How come I can say that the result of CreateLion(), a pointer to a struct that implements the Cat interface, is an instance of

4条回答
  •  粉色の甜心
    2021-02-07 09:05

    The problem here is that statically typed go differentiates the "this is a function that returns a cat" from "this is a function that returns a lion that is a cat" And therefore will not accept one as the other.

    The way to fix this is to give your factory var exactly what it expects:

    var cf CatFactory = func() Cat{
        return CreateLion()
    }
    catlion := cf()
    catlion.Meow()
    

提交回复
热议问题