2017-10-11 187 views
1

有人能幫我理解爲什麼它不能使用[Error 1]和[Error 2]之類的語法嗎?爲什麼[ok 1]可能並且工作得很好。golang函數返回接口指針

基本的設計是使用Animal作爲領域的一般類型良好的領域?或者有什麼不好的事情?或建議更好的解決方案?

package main 

import (
    pp "github.com/davecgh/go-spew/spew" 
) 

type Cat struct { 
    Name string 
    Age int 
} 

type Animal interface{} 

type House struct { 
    Name string 
    Pet *Animal 
} 

func config() *Animal { 

    c := Cat{"miao miao", 12} 
    // return &Animal(c) //fail to take address directly  [Error 1] 
    // return &(Animal(c)) //fail to take address directly  [Error 2] 
    a := Animal(c)  //[Ok 1] 
    return &a 
} 

func main() { 
    pp.Dump(config()) 
    pp.Dump(*config()) 
    pp.Dump((*config()).(Cat)) //<-------- we want this 
    pp.Dump((*config()).(Cat).Name) 
    pp.Dump("---------------") 
    cfg := config() 
    pp.Dump(&cfg) 
    pp.Dump(*cfg) 
    pp.Dump((*cfg).(Cat)) //<-------- we want this 
    pp.Dump((*cfg).(Cat).Name) 
    pp.Dump("---------------") 
} 

回答

3

好吧,二事:

  1. 不能直接採取轉換的結果的地址,因爲它不是「可尋址」。有關更多信息,請參閱section of the spec about the address-of operator
  2. 爲什麼你使用一個指向接口的指針呢?在我所有的項目中,我只使用過一次接口指針。接口指針基本上是指向指針的指針,有時需要,但非常少見。內部接口是一個類型/指針對。所以除非你需要修改接口值而不是的值,那麼接口會保存,那麼你不需要一個指針。 This post可能會對您感興趣。