【问题标题】:golang function return interface pointergolang函数返回接口指针
【发布时间】:2018-03-22 12:44:17
【问题描述】:

有人能帮我理解为什么它不能使用像 [Error 1] 和 [Error 2] 这样的语法吗?为什么 [ok 1] 是可能的并且工作得很好。

使用 Animal 作为字段作为泛型类型的基本设计好吗?或者有什么不好的地方吗?或者有什么更好的解决方案?

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("---------------")
}

【问题讨论】:

    标签: pointers go syntax interface


    【解决方案1】:

    好的,两件事:

    1. 您不能直接获取转换结果的地址,因为它不是“可寻址的”。请参阅section of the spec about the address-of operator 了解更多信息。
    2. 为什么要使用指向接口的指针?在我所有的项目中,我只使用过一次接口指针。接口指针基本上是指向指针的指针,有时需要,但非常少见。内部接口是类型/指针对。因此,除非您需要修改 接口值 而不是 接口持有的值,否则您不需要指针。 This post 您可能感兴趣。

    【讨论】:

    • 我喜欢那篇博文——它很好,很清晰,谢谢!这也让我困惑了一段时间:)
    猜你喜欢
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 2013-04-10
    • 1970-01-01
    相关资源
    最近更新 更多