9
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

Goのスライスをポインタ渡しした時のindexアクセスの書き方

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

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にアクセスできる。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
9
Help us understand the problem. What are the problem?