[問題] Golang的interface

看板Programming作者 (用功點吧!)時間6年前 (2018/01/12 18:52), 編輯推噓3(303)
留言6則, 3人參與, 6年前最新討論串1/1
小弟剛從Python轉Golang,有些關念還不是很清楚,請大家指教一下。 我有一個 Interface,定義兩個 method 如下: type Content interface{ GetContent(filters map[string]string) (Content, error) GetContents(filters map[string]string) ([]*Content, int64, error) } 然後實做 struct 如下 type MyContent struct { TypeA blablabla TypeB blablabla } func (t *MyContent) GetContent(filters map[string]string) ( item Content, err error) { item = &MyContent{} // do something, 這個function 可以work } # 這個function可以work,可以透過實做 interface 來達到我想要的功能 func (t *MyContent) GetContents(filters map[string]string) ( items []*Content, total int64, err error) { err = nil items = []&MyContent{} #^^^^^^^^^^^^^^^^^^^^^ 死在這行 #cannot use []MyContent literal (type []MyContent) as type []*Content in #assignment 但第二個function一直出現錯誤,請問我該怎麼解呢?感謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 211.22.61.74 ※ 文章網址: https://www.ptt.cc/bbs/Programming/M.1515754360.A.FE6.html

01/12 20:13, 6年前 , 1F
[]*MyContent{}
01/12 20:13, 1F

01/12 20:31, 6年前 , 2F
試過了,一樣orz 感謝
01/12 20:31, 2F

01/12 22:01, 6年前 , 3F
因為您的return要的是Content,但宣告是M
01/12 22:01, 3F

01/12 22:01, 6年前 , 4F
yContent
01/12 22:01, 4F

01/13 00:15, 6年前 , 5F
您把*Content換成Content,因為interface
01/13 00:15, 5F

01/13 00:15, 6年前 , 6F
是沒指標的
01/13 00:15, 6F
文章代碼(AID): #1QM9Du_c (Programming)