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?

More than 1 year has passed since last update.

入門GOプログラミング Lesson3 ループと分岐

Last updated at Posted at 2023-03-04

bool値

Python, Javascript:("")データも”偽”とみなされるが、
Go:真の値はtrueだけ。偽の値はfalseだけ

package main

import (
	"fmt"
	"strings"// 文字列を扱うパッケージ
)

func main() {
	var command = "walk outside"
	var exit = strings.Contains(command, "outside")// commad文字列は"outsideを含むか(return bool)"
	fmt.Println("out cave", exit)
}

if分岐

package main
import (
	"fmt"
)
func main() {
	var age = 1
	if age >= 20 {
		fmt.Println("飲酒喫煙OKです")
	} else if 10 < age && age < 20 {
		fmt.Println("飲酒喫煙NGです")
	} else {
		fmt.Println("まさかそんな人いないよね!?")
	}
}
  • if XXXXif (XXXX)にしてもOK
  • or演算は||を使用する

switch分岐

func main() {
	var age = 20
	switch {//case内部でbool値を比較する場合はswitch XXの記述は不要
	case (age >= 20):
		fmt.Println("飲酒喫煙OKです")
	case (10 < age && age <= 20):
		fmt.Println("飲酒喫煙NGです")
	default:
		fmt.Println("まさかそんな人いないよね!?")
	}
}

switchXXを必要とするとき

func main() {
	var name = "hoge"
	switch name {
	case "hoge":
		fmt.Println("Good day!")
	case "huga":
		fmt.Println("nice!")
        fallthrough// C, Java, Javascriptではデフォルト
	default:
		fmt.Println("wonderful!")
	}
}

ループ文

func main() {
	var i = 0
	const stopNum = 10
	for i < stopNum { // 条件を記述
		fmt.Println(i)
		if i == 7 {
			fmt.Println("break!")
			break // ループからブレイクアウト
		}
		i++
	}
}

■練習問題(数あてゲーム)解答例

func main() {
	var randNum = rand.Intn(100)
	const collectNum = 49
	switch {
	case collectNum == randNum:
		fmt.Printf("randNum : %v, just collect!!", randNum)
	case collectNum > randNum:
		fmt.Printf("randNum : %v, too small", randNum)
	case collectNum < randNum:
		fmt.Printf("randNum : %v, too big", randNum)
	default:
		fmt.Printf("error")
	}
}

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?