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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号