Go – 包含切片的接口无法编译通过

huangapple go评论71阅读模式
英文:

Go - Interface containing slice wont compile

问题

这段代码在声明接口时出现了语法错误。在接口中,不能直接声明切片类型。接口只能包含方法的签名,而不能包含具体的字段。如果想要在接口中使用切片类型,可以将其定义为方法的参数或返回值。以下是修正后的代码示例:

type MyType interface {
    GetMyStringSlice() []string
}

type MyStruct struct {
    MyStringSlice []string
}

func (s MyStruct) GetMyStringSlice() []string {
    return s.MyStringSlice
}

这样,你可以通过实现GetMyStringSlice方法来获取切片类型的值。

英文:
type MyType interface {
    MyStringSlice []string
}

What is wrong with this?

It works well as a struct as in:

type MyType struct {
    MyStringSlice []string
}

but compiles with the following error when set as interface:

syntax error: unexpected [, expecting (

答案1

得分: 4

一个接口只能包含方法或其他接口。请查看语言规范

英文:

An interface can only hold methods or other interfaces. Have a look at the Language Specification.

huangapple
  • 本文由 发表于 2014年4月1日 22:47:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/22789367.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定