接口数组作为功能参数

时间:2019-02-12 21:02:20

标签: arrays go interface

如何将[]*SS实现I)传递给接受[]I作为参数的函数?

package main

import (
    "fmt"
)

type I interface {
    Method()
}

type S struct {
    Name string
}

func (s *S) Method() {
    fmt.Println(s.Name)
}

func MyFunc(i I) {
    i.Method()
}

func MyOtherFunc(i []I) {
    i[0].Method()
}

func main() {
    slist := make([]*S, 1)
    slist[0] = new(S)
    slist[0].Name = "Joe"
    MyFunc(slist[0])
    MyOtherFunc(slist)
}

游乐场:https://play.golang.org/p/9ClPgk6m69t

编译器说:

prog.go:32:13: cannot use slist (type []*S) as type []I in argument to MyOtherFunc

0 个答案:

没有答案