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

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()?

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

You would need to convert the interface{} to FakeTicker

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"}
    fakeTicker := clocker.(FakeTicker)
    fakeTicker.Tick()
}