LoginSignup
0
0

[翻訳転載] Golang Tip #9: コンパイル時のインターフェイス検証

Posted at

はじめに

本記事は以下のツイートの翻訳転載です。

コンパイル時のインターフェイス検証

Write()関数を持つBufferインターフェースと、
それを実装したStringBuffer構造体を想像してほしい。

以下のように、誤ってWrite()ではなくWriteee()のようにタイプミスをした関数を実装してしまった場合、

image

The error isn't caught until runtime. By using the trick below, the compiler will alert you with an IDE error message:
エラーは実行時まで発見されません。

しかし、以下のようにすることで、実際に実行するより前に、エディタがエラーメッセージで警告してくれます。

image

おわりに

Goでは明示的にインターフェースの実装が示されない(良くも悪くも)ので、

// 明示的なインターフェースの実装
// StringBufferがBufferの実装であることがわかる
class StringBuffer implements Buffer

このインターフェースを実装するという意図がコードから読み取れるようになるので良いなと思った。
実装の定義の直下に1行足しておくだけで導入できるのも良い。

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