Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare variable types for loop variables in Go?

See this code.

package main

import (
    "fmt"
)

func main() {
    var arr [4]string = [4]string{"foo", "bar", "baz", "qux"}

    for a, b := range arr {
        fmt.Println(a, b)
    }

    // How can I fix this code?
    /*
    for x int, y string = range arr {
        fmt.Println(a, b)
    }
    */
}

The first for loop uses the := operator to automatically deduce the types of a and b. But what if I want to explicitly specify the types of the loop variables? My attempt to do this is in the second block of commented code which of course failed with the following error.

# command-line-arguments
./foo.go:15: syntax error: unexpected name, expecting {
./foo.go:18: syntax error: unexpected }

Can you help me fix the second block of code such that I can specify the types of x and y explicitly?

like image 715
Lone Learner Avatar asked Apr 23 '17 05:04

Lone Learner


3 Answers

Unfortunately the language specification doesn't allow you to declare the variable type in the for loop. The closest you could get is this:

var a int
var b string
for a, b = range arr {
    fmt.Println(a, b)
}

But normally if you give your variable meaningful names, their type would be clear as well:

for index, element := range arr {
    fmt.Println(index, element)
}
like image 192
Darin Dimitrov Avatar answered Sep 21 '22 06:09

Darin Dimitrov


You need to declare first the vars.

var x int
var y string ...// now it should be ok.

for x,y = range arr {
    fmt.Println(x, y) // it should be x and y instead of a,b
}

Check the fiddle

like image 27
Riad Avatar answered Sep 22 '22 06:09

Riad


First of all your code is not a valid Go code. The for range loop returns the index and the value of an array, slice, string, or map, so there is no reason the explicitly specify the type of the value and the index.

You are specifying the type of the values at the variable initialization, and the language will deduce the type on the range iteration.

One special case is when you are using interface{} as variable type. In this case, you if you need to know the type of the value you can use the reflect package to deduce the type of the value.

switch reflect.TypeOf(t).Kind() {
case reflect.Slice:
    s := reflect.ValueOf(t)

    for i := 0; i < s.Len(); i++ {
        fmt.Println(s.Index(i))
    }
}
like image 25
Endre Simo Avatar answered Sep 22 '22 06:09

Endre Simo