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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目
  • ¥15 数电几道习题,写出作答过程,ai一律不采用
  • ¥15 利用pthon计算薄膜结构的光导纳
  • ¥15 海康hlss视频流怎么播放
  • ¥15 Paddleocr:out of memory error on GPU
  • ¥30 51单片机C语言数码管驱动单片机为AT89C52