2017-10-11 181 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可能会对您感兴趣。