3
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 3 years have passed since last update.

Go for文の"_"の使い方

Last updated at Posted at 2020-01-21

golangのfor文を勉強していて

"_"の意味を理解したのでまとめておきます。

結論から言いますと

インデックス番号を表示する必要がない場合に
"_"を使います。

main.go
package main

import "fmt"

func main(){

    //スライス作成
	l := []string{"jave", "python", "go"}

    //インデックス番号とスライスの要素を表示
	for i:=0; i < len(l); i++{
		fmt.Println(i, l[i])
	}
    //スライスの要素だけを表示
	for  _, v := range l{
		fmt.Println(v)
	}

    //"_"を使わずに要素を表示させようとすると
    for  v := range l{
		fmt.Println(v)
	}
    //インデックス番号が表示される
    //"_"でインデックス番号を埋める必要がある
 

    //map作成
	m := map[string]int{"apple": 100, "banana":200}

    //mapのキーと値を表示	
	for k, v := range m{
		fmt.Println(k, v)
	}

    //mapのキーを表示
	for k := range m{
		fmt.Println(k)
	}

    //mapの値を表示
	for _, v := range m{
		fmt.Println(v)
	}
}
3
0
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
3
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?