dpp66953 2013-06-04 11:18
浏览 56
已采纳

在Go中,如何使用匿名字段方法获取TypeOf类型?

How do I get the correct Type of the struct using the anonymous field (or superclass)?

I am trying to make this fish describe itself as a cod:

package main

import (
    "fmt"
    "reflect"
)

type Fish struct {
}

func (self *Fish) WhatAmI() string {
    return reflect.TypeOf(self).String()
}

type Cod struct {
    Fish
}

func main() {
    c := new(Cod)
    fmt.Println("I am a", c.WhatAmI())
}

The output I get is:

I am a *main.Fish

What I want is:

I am a *main.Cod
  • 写回答

2条回答 默认 最新

  • doumengjing1500 2013-06-04 11:26
    关注

    You are getting the correct answer. The answer you want to get is wrong.

    In

    func (f *Fish) WhatAmI() string {
            return reflect.TypeOf(f).String()
    }
    

    f is of type *main.Fish, it's even declared to be of that type (f *Fish). Thus it cannot ever be of type *main.Cod.

    The probable source of confusion: The method set of Cod inherites the method set of its embedded, anonymous field Fish and doesn't override it. Thus invoking WhatAmI on an instance of Cod "delegates" the call to Fish.WhatAmI, but the receiver is now the embedded field of type *main.Fish.

    Example with overriding the inherited method:

    package main
    
    import (
            "fmt"
    )
    
    type Fish struct {
    }
    
    func (f *Fish) WhatAmI() string {
            return fmt.Sprintf("%T", f)
    }
    
    type Cod struct {
            Fish
    }
    
    func (c *Cod) WhatAmI() string {
            return fmt.Sprintf("%T", c)
    }
    
    func main() {
            c := new(Cod)
            fmt.Println("I am a", c.WhatAmI())
    }
    

    Playground


    Output:

    I am a *main.Cod
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 eclipse连接sap后代码跑出来空白
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案