How to declare variable types for loop variables in Go?

huangapple go评论157阅读模式
英文:

How to declare variable types for loop variables in Go?

问题

看到这段代码。

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

	// 我该如何修复这段代码?
	/*
	for x int, y string = range arr {
		fmt.Println(a, b)
	}
	*/
}

第一个for循环使用:=运算符自动推断ab的类型。但是如果我想显式指定循环变量的类型怎么办?我尝试在第二个被注释的代码块中这样做,但是当然会失败,并显示以下错误。

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

你能帮我修复第二个代码块,以便我可以显式指定xy的类型吗?

英文:

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?

答案1

得分: 3

很抱歉,语言规范不允许在for循环中声明变量类型。你能做的最接近的方式是这样的:

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

但通常情况下,如果你给变量起有意义的名字,它们的类型也会很清晰:

for index, element := range arr {
	fmt.Println(index, element)
}
英文:

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

答案2

得分: 2

你需要首先声明 vars

var x int
var y string ...// 现在应该没问题了。

for x,y = range arr {
    fmt.Println(x, y) // 应该是 x 和 y 而不是 a 和 b
}

请查看 fiddle

英文:

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

答案3

得分: 2

首先,你的代码不是有效的Go代码。for range循环返回数组、切片、字符串或映射的索引和值,所以没有必要显式指定值和索引的类型。

你在变量初始化时指定了值的类型,语言会在range迭代中推断出类型。

一个特殊情况是当你使用interface{}作为变量类型时。在这种情况下,如果你需要知道值的类型,可以使用reflect包来推断值的类型。

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

    for i := 0; i < s.Len(); i++ {
        fmt.Println(s.Index(i))
    }
}
英文:

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 &lt; s.Len(); i++ {
        fmt.Println(s.Index(i))
    }
}

答案4

得分: 0

这是一个Go语言的代码片段,它尝试在同一行中声明两种不同类型的数据,这是不可能的。如果你想显式声明变量,你需要在使用之前先声明它们,就像上面的答案一样。但是,如果你想让它们成为其他类型,你需要根据你的需求进行转换。

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

请注意,这只是一个代码片段,它将字符串数组转换为字节数组并打印出来。

英文:

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 (
	&quot;fmt&quot;
)

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

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

huangapple
  • 本文由 发表于 2017年4月23日 13:56:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/43567914.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定