0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Golangの構造体のポインタ配列

Posted at

Golangの構造体のポインタ配列

Golangの構造体(Golangでなくてもそうかも)は、メモリ使用量が地味に多いので、ポインタ配列を使いまくるのがコストパフォーマンス面で良さそうなので使いまくるために備忘録。

使いまくるポインタ例

type Account struct{
	id int
	name  string
}

でこういうのたち。ポインタとポインタの配列。

*Account
[]*Account

こっちじゃない。これは配列のポインタ。

*[]Account

ポインタ配列

ポインタ配列の方が速い。使いまくる。

package main

import (
	"fmt"
)

// todo
// requirement
// Account is struct
// Accounts has an Account array defined as a pointer in field

type Account struct {
	id   int
	name string
}

type Accounts struct {
	accounts []*Account
}

func main() {

	// ポインタ型の値を作る
	var a1 *Account = &Account{id: 123, name: "foo"}
	var a2 *Account = &Account{id: 456, name: "bar"}

	// ポインタ型の配列を作る
	var as []*Account = []*Account{a1, a2}

	var acs Accounts = Accounts{accounts: as}

	// 各要素のメモリアドレスが表示される
	fmt.Println(acs)
	// {[0x14000126018 0x14000126030]}

	// ループで配列の要素にアクセスする
	for _, a := range acs.accounts {
		// *演算子で変数の値にアクセスする。
		fmt.Println(*a)
	}
	// {123 foo}
	// {456 bar}

}

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?