LoginSignup
2
2

More than 3 years have passed since last update.

ある型があるinterfaceを実装しているかを保証する

Posted at

目的

ある型がinterfaceを実装しているかを保証したい。

環境

Go: go1.14 darwin/amd64

サンプルコード

package main

// 適当なinterfaceを定義する。
type Somether interface {
    Method() bool
}

// 適当な type alias を定義する。Sometherを満足することを期待する。
type MyType string

// メソッドリストにないメソッドを定義する。つまりインターフェースを満足していない。
func (m *MyType) Method2() bool {
    return true
}

// Somether型の変数を定義する。変数は利用しないので _ で無視する。
// インターフェース値の型にMyType型のポインタ、値はnilをアサインする。
var _ Somether = (*MyType)(nil)

func main() {}

// 実行結果
// cannot use (*MyType)(nil) (type *MyType) as type Somether in assignment:
// *MyType does not implement Somether (missing Method method)

playground

標準パッケージ

標準パッケージでも一部実装されている箇所がある。以下、一例。

参考

2
2
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
2
2