我有如下示例所示的Tag結構和接口。TableAbstruct[標簽結構]type Tag struct { Id int `db:"id"` Name string `db:"Name"`}func (tag Tag) Serialize() []string { ...}[TableAbstruct 接口]type TableAbstruct interface { Serialize() []string}Xxx()函數返回[]TableAbstruct,但實際類型是[]Tag。下面的程序將運行良好,因為Tag包含TableAbstruct接口。func Xxx() []TableAbstruct { result := []TableAbstruct{} for i := 0; i < 10; i++ { table_obj := Tag{} result = append(result, table_obj) } return result}但我想像下面這樣寫,但我不能。我認為問題是TypeError。但是我不明白為什么會發生錯誤。func Xxx() []TableAbstruct { result := []Tag{} return result}
1 回答

慕尼黑8549860
TA貢獻1818條經驗 獲得超11個贊
Go 對切片和類型沒有任何幻想。簡而言之,如果您說要返回[]TableAbstruct,則必須準確返回。所以如果你想返回 a []Tag,你必須創建一個切片[]TableAbstruct然后手動填充它:
func Xxx() []TableAbstruct {
var returnValue []TableAbstruct
for _, t := range result {
returnValue = append(returnValue, t)
}
return returnValue
}
- 1 回答
- 0 關注
- 158 瀏覽
添加回答
舉報
0/150
提交
取消