14

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?

5
  • Possible duplicate of variable declaration in init statement of for loop Commented Apr 23, 2017 at 6:02
  • Why do you want to do that? There's probably a better solution. Commented Apr 23, 2017 at 6:20
  • 1
    @Flimzy I want to do that to learn if it is possible or not in the Go language. Commented Apr 23, 2017 at 7:49
  • It's not possible to do that in Go. It is possible to accomplish the same goals in other ways, depending on what your exact needs are. Commented Apr 23, 2017 at 7:53
  • Possible duplicate of In Go, how can I automatically coerce my loop index into an uint? Commented Apr 23, 2017 at 14:26

4 Answers 4

9

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)
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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))
    }
}

5 Comments

Is there a reason to explicitly specify the type of the variable in this statement: var a int = 10? I guess not. Why is this allowed then?
Yes, there is. Taken from your example, 10 is a valid value for any numeric type e.g. byte/int16/int/int64. If you don't specify the type explicitly, the compiler will deduced the type as an int. If you want to declare a variable other than int, you need to specify it explicitly: var x float32 = 10
@putu How about var s string = "Foo"? Is there a reason to explicitly specify the type of the variable in this statement?
Quoting from the language specification (golang.org/ref/spec#Short_variable_declarations): "Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original."
If the type of right hand value is "unique", you don't need to specify the variable type explicitly. Specifying the type explicitly will make the declaration much longer without added information (compared to short version).
-1

It's not possible as you are trying to declare two different types of data in same line, if you want explicitly declare variables, then you need to declare them before itself like above answers, but if you want them to be of other type then you need to covert them as for your needs,

package main

import (
    "fmt"
)

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

    var x int64
    var b []byte
    for x = 0; x < int64(len(arr)); x++ {
        b = []byte(arr[x])
        fmt.Println(x, b)
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.