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?

More than 5 years have passed since last update.

Golangのinterfaceのポインタ配列

Last updated at Posted at 2019-08-31

やりたかったこと

interfaceのpointerの配列を作りたかった。

やったこと

  1. interfaceのポインタ配列を作る。
  2. interfaceを実装した構造体を作る。
  3. その構造体のポインタをinterfaceのポインタ配列に入れる。

作成したサンプルコードは下記の通り。

vehicle.go
package main

import "fmt"

type Vehicle interface {
	Name() string
}

type Car struct {
	name string
}

type Train struct {
	name string
}

func (c *Car) Name() string {
	return c.name
}

func (t *Train) Name() string {
	return t.name
}

func main() {
	vs := make([]*Vehicle, 2)
	var car Car
	var train Train
	car.name = "car"
	train.name = "train"
	vs[0] = &car
	vs[1] = &train
	for i := range vs {
		fmt.Println("vs[i] is " + vs[i].Name())
	}
}

上のコードを作成して実行してみると、

cannot use &car (type *Car) as type *Vehicle in assignment:
	*Vehicle is pointer to interface, not interfacego

と出る。 調べると
stackoverflow

An interface can store either a struct directly or a pointer to a struct.

と書いてあった。

なので、下記のようにすれば解決。

vs := make([]Vehicle, 2)
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?