LoginSignup
1
1

More than 5 years have passed since last update.

interface型でない変数の型アサーション

Posted at

型アサーション

t, ok := x.(T)

のxはinterface型でないといけないので
interface型でない変数に対してメソッドを実装してるかどうか確認するには
一度interface型にキャストしないといけないらしい。

type Tester interface {
    Test()
}

type A struct{}

func (a A) Test() {
    fmt.Println("called A.Test()")
}

func main() {
    a := new(A)
    tester, ok := interface{}(a).(Tester)
    //tester, ok := a.(Tester) //ERROR!
    fmt.Println("a is a Tester:", ok)
    tester.Test()
}

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1