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

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧