12
9

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のスライスをポインタ渡しした時のindexアクセスの書き方

Last updated at Posted at 2018-07-05

記述方法でハマったので備忘録として

sample.go
package main

import "fmt"

type Item struct {
	name string
}

type Items []Item

func main() {
	items := make(Items, 0)
	items = append(items, Item{name: "ペン"})
	items = append(items, Item{name: "ハサミ"})

	fmt.Println(items[0])
	fmt.Println(items[1])

	refItems := &items

	fmt.Println((*refItems)[0])
	fmt.Println((*refItems)[1])
}

itemsは[0]とアクセスできるが、refItemsは[0]と記述するとエラーになる。(does not support indexing)
(*refItems)[0]と記述する事で配列のindexにアクセスできる。

12
9
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
12
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?