doushuo1080 2015-05-09 11:10
浏览 57
已采纳

类型,接口和指针

I have a simple code:

type Namer interface {
    PrintName()
}

type P struct {
    Name string
}

func (p *P) PrintName() {
    fmt.Printf("%s
", p.Name)
}

func main() {
    p := P{Name: "Name"}

    var namers []Namer
    namers = append(namers, &p)
    fmt.Println(reflect.TypeOf(namers[0]))

    on := &namers[0]
    fmt.Println(reflect.TypeOf(on))
    (*on).PrintName()
    (**on).Name = "EEEE"
    (*on).PrintName()
}

and bunch of questions :)

  1. Why I cannot write: append(namers, p)? &p is a pointer to P, array namers is not a array of pointers
  2. Why TypeOf(namers[0]) is *P and TypeOf(on) is *Namer? It does not make sense, TypeOf(&(*P)) should be **P
  3. Why the last line print: "Name" instead of "EEE"?

Thanks for help!

  • 写回答

3条回答 默认 最新

  • duanjia2415 2015-05-09 12:30
    关注
    1. P doesn't implement interface Namer, only *P does, as PrintName() is defined on *P.

    2. As I understand it, TypeOf(namers[0]) is *P because you're inspecting the actual slice element itself, and TypeOf can see inside the interface. With TypeOf(&namers[0]) you're merely taking the address of the first element and inspecting its type (which is, of course, *Namer, as namers is a slice of Namer interface elements), without actually looking "inside" the element itself.

    3. The last line doesn't print anything, because (**on).Name is not allowed. Change it to (*on).(*P).Name = "EEEE" and it works as intended.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行