duanban4769
2017-10-11 00:53
浏览 75
已采纳

golang函数返回接口指针

Can some one help me understand why it's failing to use the syntax like [Error 1] and [Error 2]?, why [ok 1] is possible and working just fine.

Is the basic design to use Animal as field to serve as generic type good? or any thing bad about it? or any better solution suggested?

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("---------------")
}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题