作者Nt1 (用功點吧!)
看板Programming
標題[問題] Golang的interface
時間Fri Jan 12 18:52:37 2018
小弟剛從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
推 s25g5d4: []*MyContent{} 36.225.19.49 01/12 20:13
→ Nt1: 試過了,一樣orz 感謝 123.192.211.62 01/12 20:31
推 tommady: 因為您的return要的是Content,但宣告是M 42.115.102.87 01/12 22:01
→ tommady: yContent 42.115.102.87 01/12 22:01
推 tommady: 您把*Content換成Content,因為interface 42.115.102.87 01/13 00:15
→ tommady: 是沒指標的 42.115.102.87 01/13 00:15