dsgdfh302506 2016-02-16 21:25
浏览 46
已采纳

接口和类型的问题

Can someone please explain as to why duck typing does not work when a slice is passed to the variadic function.
Cases 1 and 2 as indicated below seems to work, but case-3 below initializes a slice and thereafter passes the dereferenced slice to the function that accepts the interface.

The error message is : cannot use gophers (type []Gopher) as type []Animal in argument to runForest

package main

    import (
        "fmt"
    )

    type Animal interface {
        Run() string
    }

    type Gopher struct {
    }

    func (g Gopher) Run() string {
        return "Waddle.. Waddle"
    }

    func runForest(animals ...Animal) {
        for _, animal := range animals {
            fmt.Println(animal.Run())
        }
    }

    func main() {

        //works
        runForest(Gopher{})

        //works
        runForest(Gopher{},Gopher{})

        // does not work
        gophers := []Gopher{{},{}}
        runForest(gophers...)
    }
  • 写回答

1条回答 默认 最新

  • dongzou7134 2016-02-16 21:35
    关注

    As Volker mentions in the comments, slices can't be implicitly converted the way their elements can. A Gopher can quack like an Animal, but a []Gopher can't quack like an []Animal.

    The minimal change to get this working is:

    func main() {
        gophers := []Gopher{{}, {}}
        out := make([]Animal, len(gophers))
        for i, val := range gophers {
            out[i] = Animal(val)
        }
        runForest(out...)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决