range over slice of floats but compiler thinks they are ints

192 views
Skip to first unread message

Stanley Iriele

unread,
Feb 9, 2012, 5:53:50 PM2/9/12
to golang-nuts, DeeDar...@gmail.com

Hello, I am writing a little test class to understand the math
packages a little more. I created a slice literal of float64 and when
i range over it i get :

main.go:14: cannot use value (type int) as type float64 in function
argument

here is the code. there's nothing complicated going on here but can
someone explain to me how the compiler is coming up with this or if I
am doing something wrong?

{Code}package main

import (
"math"
"fmt"
)

func main (){
fmt.Println("Yooo")
var values = []float64{0.0, 45.0, 60.0, 90.0, 120.0, 180.0,
270.0,330.0}

for value := range values {
sin, cos := math.Sincos(value)
fmt.Println("sin: ",sin, " cos: ", cos)
}
}{Code}

Mostafa Hajizadeh

unread,
Feb 9, 2012, 6:00:54 PM2/9/12
to golan...@googlegroups.com, DeeDar...@gmail.com
Change "for value := range values" to "for _, value := range values".

Read more here.

Jonathan Pittman

unread,
Feb 9, 2012, 6:01:11 PM2/9/12
to Stanley Iriele, golang-nuts, DeeDar...@gmail.com
When you range over a slice, you get two values back.  The first value is the index value of the element.  The second value is the element itself.  What you want is...

for _, value := range values {

Archos

unread,
Feb 9, 2012, 6:06:44 PM2/9/12
to golang-nuts
The first element that return a range is a counter which is an integer

for _, value := range values {

Kyle Lemons

unread,
Feb 9, 2012, 6:06:37 PM2/9/12
to Jonathan Pittman, Stanley Iriele, golang-nuts, DeeDar...@gmail.com
Don't think of for...range as for...each.  It iterates over the range of keys/indices, and can optionally also give you the values.

Stanley Iriele

unread,
Feb 9, 2012, 5:57:42 PM2/9/12
to golang-nuts
ok it looks like its just returning the index's I guess I assumed it
was like a foreach loop.. my mistake

Stanley Iriele

unread,
Feb 9, 2012, 6:42:48 PM2/9/12
to golang-nuts
Ahh....I see I see....wow you guys respond fast..I appreciate that

Charlie Dorian

unread,
Feb 9, 2012, 11:14:16 PM2/9/12
to golang-nuts
Also -- if you don't get the results you expect, please note that the
trig function arguments are radians, not degrees.
Reply all
Reply to author
Forward
0 new messages