1
2

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 1 year has passed since last update.

構造体の中にスライス(string)を持っているやつの初期化方法

Posted at

やりたいこと

柔軟に値を出し入れできる構造体を使いたい。
例えば、こんな構造体を初期化したい

type Account struct {
	asset     []string 
	liability []string 
	benefit   []string 
	cost      []string 
}

結論

初見じゃ思いつかんです。
なおポインタへの代入だとまた変わったりするらしい

	var defSubjects Account = Account{
		asset:     []string{"cash", "bank"},
		benefit:   []string{"salary"},
		cost:      []string{"food", "water", "phone"},
		liability: []string{"loan"},
	}

「参考」筆者がやらかした間違った方法

	var defSubjects Account = Account{
		asset:     {"cash", "bank"},
		benefit:   {"salary"},
		cost:      {"food", "water", "phone"},
		liability: {"loan"},
	}
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?