golang 函数返回接口指针

Ste*_*eng 3 syntax pointers interface go

有人可以帮助我理解为什么它无法使用 [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("---------------")
}
Run Code Online (Sandbox Code Playgroud)

Mil*_*sen 10

好的,两件事:

  1. 您不能直接获取转换结果的地址,因为它不是“可寻址的”。有关更多信息,请参阅规范中有关 address-of 运算符部分
  2. 为什么要使用指向接口的指针?在我所有的项目中,我只使用过一次接口指针。接口指针基本上是指向指针的指针,有时需要,但非常少见。内部接口是一个类型/指针对。因此,除非您需要修改接口值而不是接口保存值,否则您不需要指针。您可能对这篇文章感兴趣。