dongzhiqi0332 2018-02-14 19:45
浏览 109
已采纳

如何访问接口中未定义的类型方法?

I have interface that requires its implementor to have Click method. However, the type FakeTicker that implements this interface also implements Tick method in addition to Click method.

package main



type Ticker interface{  
  Click() string 
}

type FakeTicker struct{ 
   val string }

func (f FakeTicker) Click() string {    
   return f.val 
}

func (f FakeTicker) Tick() int {    return 1 }

func main() {   
  var clocker Ticker    
  clocker = FakeTicker{"Val"}   
  clocker.Tick()    
}

Here I get the following error "clocker.Tick undefined (type Ticker has no field or method Tick)"

I understand that the interface only has method Click() but since FakeWriter is implementing the interface, Shouldn't it be able to call its own method Tick()?

  • 写回答

2条回答 默认 最新

  • 普通网友 2018-02-14 19:54
    关注

    I understand that the interface only has method Click() but since FakeWriter is implementing the interface, Shouldn't it be able to call its own method Tick()?

    Since your clocker variable is defined as the Ticker interface, you only have the methods defined on that interface. If you would like to access the Tick method, you will have to change to the FakeTicker type.

    In this case, you can use type assertion.

    func main() {   
        var clocker Ticker    
        clocker = FakeTicker{"Val"}
        clocker.Click()
        fake := clocker.(FakeTicker)
        fake.Tick()    
    }
    

    You should note that the type assertion will cause a panic when the assertion fails if you don't use the version with two return types (fake, ok := clocker.(FakeTicker)).

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

报告相同问题?

悬赏问题

  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?