Arrays

var x [5]int
x[4] = 1000
fmt.Println(x)
var total float64 = 0
for i := 0; i < len(x); i++ {
	total += x[i] 
}
fmt.Println(total / len(x))

⇒ 에러 뜬다.

$ go run tmp.go
# command-line-arguments
.\\tmp.go:19: invalid operation: total / 5 
(mismatched types float64 and int)

⇒ 수정 필요.

var total float64 = 0
for i, value := range x {
	total += value 
}
fmt.Println(total / float64(len(x)))

⇒ 다른 에러가 뜬다.

$ go run tmp.go
# command-line-arguments 
.\\tmp.go:16: i declared and not used

⇒ 고 컴파일러는 변수를 만들고 사용하지 않는 것을 허용하지 않는다.

var total float64 = 0
for _, value := range x {
	total += value 
}
fmt.Println(total / float64(len(x)))

⇒ 이렇게 바꿔주면 된다. _를 사용하면 사용하지 않는 변수라고 컴파일러에게 말하는 게 된다.

추가적으로 짧게 쓸 수 도 있다.

x := [5]float64{ 98, 93, 77, 82, 83 }

or

x := [5]float64{ 
		 98,
     93,
     77,
     82,
     83,
}