dongxing2302 2018-10-30 12:24
浏览 16
已采纳

无法使用实现接口的结构

This question already has an answer here:

code:

package main

import "fmt"

type implementation struct {
    d []int
}

func (impl *implementation) getData() interface{} {
    return impl.d
}

type phase struct{}

type data interface {
    getData() interface{}
}

func MakeIntDataPhase() *phase {
    return &phase{}
}

func (p *phase) run(population []data) []data {
    return nil
}

func main() {
    var population []implementation
    MyPhase := MakeIntDataPhase()
    fmt.Println(MyPhase.run(population))

}

When running following code in playground I got following error: prog.go:30:25: cannot use population (type []implementation) as type []data in argument to MyPhase.run

I am new to golang and I don't understand why is this happening?

Struct implementation implements method getData() from data interface. Isn't it enough to use a slice of implementation in run method?

Where my reasoning is wrong?

</div>
  • 写回答

1条回答 默认 最新

  • douyue1998 2018-10-30 12:32
    关注

    This seems counter-intuitive but []data is of a different type to []implementation because of how slice types are represented in Go.

    This is actually discussed in the the Go Wiki

    Edit: Consider this

    var impl []*implementation
    var data []data = impl
    

    The compiler will complain with

    cannot use impl (type []*implementation) as type []data in assignment
    

    It's more code but you actually have to create a slice of your interface as what the comments in this thread recommends, like so:

    var impl []*implementation
    var data []data
    
    // assuming impl already has values
    for _, v := range impl {
        data = append(data, v)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?