7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ポインタレシーバでメソッド実装した型は、実体をインターフェースで受けられない

Posted at

はじめに

題名の通りです。使用言語がJavaからGolangへ変わり、ポインタで苦しんでおります。

前提

// インターフェース
type MyInterface interface {
	method1() int
	method2() int
}

// レシーバー
type MyStruct struct {
	int1 int
	int2 int
}

func (s MyStruct) method1() int { return s.int1 }
func (s MyStruct) method2() int { return s.int2 }

// ポインタレシーバー
type MyStructWithPtrReceiver struct {
	int1 int
	int2 int
}

func (s *MyStructWithPtrReceiver) method1() int { return s.int1 }
func (s *MyStructWithPtrReceiver) method2() int { return s.int2 }

ポインタについておさらい

var myStruct1 MyStruct = MyStruct{}
var ptrOfMyStruct1 *MyStruct = &MyStruct{}
var ptrOfMyStruct2 *MyStruct = &myStruct1
var myStruct2 MyStruct = *ptrOfMyStruct1
/*
 * mystruct MyStruct ---(&myStruct)---------------------> *Mystruct
 *
 *          MyStruct <--(*ptrOfMyStruct)--- ptrOfMyStruct *MyStruct
 */
  • Struct型のポインタ型は*Struct
  • &structで実体structからポインタを取得
  • *pointerでポインタpointerから実体を取得

今回のハマりポイント

var myIF1 MyInterface = MyStruct{}
var myIF2 MyInterface = &MyStruct{}
// var myIF3 MyInterface = MyStructWithPtrReceiver{} -> コンパイルエラー
var myIF4 MyInterface = &MyStructWithPtrReceiver{}
  • 値レシーバでメソッドを実装したMyStruct
    • 実体MyStruct{}MyInterface型で受けられる
    • ポインタ&MyStruct{}MyInterface型で受けられる
  • ポインタレシーバでメソッドを実装したMyStructWithPtrReceiver
    • 実体MyStructWithPtrReceiver{}MyInterface型で受けられない
    • ポインタ&MyStructWithPtrReceiver{}ならMyInterface型で受けられる
7
4
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
7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?