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条回答 默认 最新

  • dragon_9000 2017-10-11 01:16
    关注

    Ok, two thing:

    1. You cannot take the address of the result of a conversion directly, as it is not "addressable". See the section of the spec about the address-of operator for more information.
    2. Why are you using a pointer to an interface at all? In all my projects I have only ever used an interface pointer once. An interface pointer is basically a pointer to a pointer, sometimes needed, but very rare. Internally interfaces are a type/pointer pair. So unless you need to modify the interface value instead of the value the interface holds then you do not need a pointer. This post may be of interest to you.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?