LoginSignup
2
0

【Go言語】シャドーイング

Last updated at Posted at 2023-12-03

シャドーイングとは

異なるスコープで同じ名前の変数が使用される場合に発生することがある
具体的には、異なるスコープで:=演算子を使って再宣言された変数はスコープ外の値に影響を及ぼさない

意図せずに異なる変数にアクセスしてしまう可能性があるので、注意が必要になる

サンプル

package main

import "fmt"

func main() {

	num := 10
	if true {
		num := 20        // シャドーイングが起きる
		fmt.Println(num) // 20
	}
	fmt.Println(num) // 10

	if true {
		num = 30         // シャドーイングが起きない
		fmt.Println(num) // 30
	}
	fmt.Println(num) // 30
}

シャドーイングを避ける方法

  1. :=の代わりに=を使う
  2. shadowを利用する
    使用方法は以下の記事が参考になる

参考

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