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条)

报告相同问题?