0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【一コマ】interfaceとstructの違いをガチャピンで例えた

0
Posted at

Claude先生にGo言語でのinterfaceとstructについて、例えが当たってるか聞いてみた。

質問

例えるなら、ガチャピンの着ぐるみがinterfaceで、やれる動作や競技・技を持ってるのがstructで、毎回ガチャピンとして違う行為をする為に、structを入れ替えて出演させられるって事で良い?

回答

Claudeの回答から引用

最高の例えです!完璧に合ってます!

その例えで整理すると

ガチャピンの着ぐるみ = interface
→ 「ガチャピンとして振る舞える」という約束だけ持っている

中の人(struct)= 実際の処理
→ スキー担当の中の人
→ スカイダイビング担当の中の人
→ テスト用のダミーの中の人
go
// ガチャピンの着ぐるみ(interface)
type Gachapin interface {
    Ski() error
    Skydive() error
}

// スキー担当の中の人(struct)
type SkiGachapin struct {
    skill string
}
func (g *SkiGachapin) Ski() error { ... }

// テスト用ダミーの中の人(struct)
type MockGachapin struct {}
func (g *MockGachapin) Ski() error { return nil }

外から見れば全部ガチャピンとして扱えるけど、中の人は自由に差し替えられる、というイメージです!

感想

これからも例えでちゃんと理解しようと思いました😅

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?