2
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?

More than 5 years have passed since last update.

Goのスコープに苦しんだ事例集

Last updated at Posted at 2019-06-07

コンパイル通るけどtestで死ぬ事例、個人的No.1のスコープ関連についてまとめ。

事例その1 メソッド完結

メソッド内でスコープ切れちゃうので、メソッド内でnewしてもダメだぜの例。
"スコープが切れる"という表現でいいのだろうか。。。

type hogehoge map[string]string

func (h hogehoge) Seter(p string) {
    h["key"] = p
}
func (h *hogehoge) NewSeter(p string) {
    h = &hogehoge{"p": p}
}

func main() {
    f := hogehoge{}
    f.Seter("ddd")
    fmt.Println(f) // <- map[key:ddd]

    f.NewSeter("sss")
    fmt.Println(f) // <- map[key:ddd]
}

そもそも、こういうことがやりたかったのでコード間違ってたんですけどね。

事例その2 ループ内部完結

=:=を間違える、よくやるやつ。

dev := "hoge"

for _, v := range []string{"a", "b"} {
    dev := v
    fmt.Println(dev) // <- "a","b"
}
fmt.Println(dev) // <- "hoge"

2
0
4

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
2
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?