在玩 Go 時(shí),我遇到了一個(gè)問題:是否可以為切片實(shí)現(xiàn)接口?我無法在任何地方找到答案。我嘗試了以下操作但沒有成功:type t1 struct { prop string}type i1 interface { toString() string}//okfunc (o t1) toString() { return o.prop}// ERROR invalid receiver []i1 (basic or unnamed type)compiler(InvalidRecv)func (o []i1) toString() {}// ERROR invalid receiver []t1 (basic or unnamed type)compiler(InvalidRecv)func (o []t1) toString() {}
1 回答
一只甜甜圈
TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超5個(gè)贊
不能為切片定義方法。您可以從切片中定義新類型,并為其定義一個(gè)方法:
type t1Slice []t1
func (o t1Slice) toString() {
}
然后你可以做:
var arr []t1
t1Slice(arr).toString()
- 1 回答
- 0 關(guān)注
- 116 瀏覽
添加回答
舉報(bào)
0/150
提交
取消
