package main
import (
"fmt"
)
func main() {
friendNames := []string{"yoshi", "mario", "peach", "bowser", "luigi"}
// local copy friendNames to value within loop
for _, value := range friendNames {
fmt.Printf("the value at index %v\n", value)
value = "new string"
}
}
// 결과
//
// the value at index yoshi
// the value at index mario
// the value at index peach
// the value at index bowser
// the value at index luigi
package main
import (
"fmt"
)
func main() {
switch i := 1; i {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
default:
fmt.Println("another number")
}
switch i := 1 + 1; i {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
default:
fmt.Println("another number")
}
var i interface{} = 1
switch i.(type) {
case int:
fmt.Println("i is an int")
case float64:
fmt.Println("i is an floate64")
case string:
fmt.Println("i is string")
default:
fmt.Println("i is another type")
}
var j interface{} = [3]int{}
switch j.(type) {
case int:
fmt.Println("j is an int")
case float64:
fmt.Println("j is an floate64")
case string:
fmt.Println("j is string")
default:
fmt.Println("j is another type")
}
}
// 결과
//
// one
// two
// i is an int
// j is another type
package main
import (
"fmt"
)
func main() {
for i, j := 0, 0; i < 5; i, j = i+1, j+1 {
// for i, j := 0, 0; i < 5; i, j = i++, j++ { // error
fmt.Println("i:", i, "j:", j)
}
fmt.Println("==========")
l := 0
for ; l < 5; l++ {
fmt.Println(l)
}
fmt.Println(l)
fmt.Println("==========")
// infinite for loop
k := 0
for {
if k == 10 {
break
}
k++
}
fmt.Println("k:", k)
fmt.Println("==========")
d := []int{1, 2, 3}
for k, v := range d {
fmt.Println("key:", k, "value:", v)
}
}
// 결과
//
// i: 0 j: 0
// i: 1 j: 1
// i: 2 j: 2
// i: 3 j: 3
// i: 4 j: 4
// ==========
// 0
// 1
// 2
// 3
// 4
// 5
// ==========
// k: 10
// ==========
// key: 0 value: 1
// key: 1 value: 2
// key: 2 value: 3
package main
import (
"fmt"
)
func main() {
// FizzBuzz
for i := 0; i <= 100; i++ {
if i%15 == 0 {
fmt.Println("FizzBuzz")
} else if i%3 == 0 {
fmt.Println("Fizz")
} else if i%5 == 0 {
fmt.Println("Buzz")
} else {
fmt.Println(i)
}
}
}
// 결과
//
// FizzBuzz
// 1
// 2
// Fizz
// 4
// Buzz
// ...
package main
import (
"fmt"
)
func main() {
friendNames := []string{"yoshi", "mario", "peach", "bowser", "luigi"}
// local copy friendNames to value within loop
for _, value := range friendNames {
fmt.Printf("the value at index %v\n", value)
value = "new string"
}
}
// 결과
//
// the value at index yoshi
// the value at index mario
// the value at index peach
// the value at index bowser
// the value at index luigi
댓글 영역