11
5

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.

[教えて]Go言語:なぜインターフェイスはポインタにできない?

Posted at

なぜ、インターフェイスはポインタにできないのでしょうか?

下記のコードのようにFooInterfaceのポインタを受け取る関数Callを定義するとコンパイルエラーになります。

package main

import "log"

type FooInterface interface {
	DoSomething()
}

type Foo struct {
}

func (this *Foo) DoSomething() {
	log.Println("Foo DoSomething was called")
}

func Call(foo *FooInterface) {
	foo.DoSomething()
}

func main() {
	Call(&Foo{})
}

エラーの内容

./main.go:17: foo.DoSomething undefined (type *FooInterface has no field or method DoSomething)
./main.go:21: cannot use Foo literal (type *Foo) as type *FooInterface in function argument:
	*FooInterface is pointer to interface, not interface

下記のようにアスタリスク * を取るとエラーがでなくなります

func Call(foo FooInterface) {
	foo.DoSomething()
}

11
5
1

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
11
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?