在for循环中定义的变量在外部是未定义的。

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

Variable in for loop undefined outside

问题

我想知道为什么下面的代码片段不起作用:

package main

import (
	"fmt"
)

func main() {
	for i := 0; i < 10000; i++ {
		var randomString = fmt.Sprintf("a%sa\n", "test")
	}
	fmt.Printf("Made 10000 random strings like", randomString)
}

我已经删除了一些无关的代码(因为这显然不是真正的随机代码)。

我遇到的问题是,在for循环的下面,"randomString"未定义。

我尝试使用randomString := fmt.Sprintf()和你上面看到的var来设置它。

我相当确定这是一个作用域问题(randomString变量在for循环外部的作用域中不可用),但作为一个PHP/JS开发者,我不习惯这种情况,并且会说变量在for循环之后也可用。

如何从那个位置访问该变量?基本上只需显示最后生成的字符串。

英文:

I am wondering why the following piece of code is not working:

package main

import (
	&quot;fmt&quot;
)

func main() {
	for i := 0; i &lt; 10000; i++ {
	    var randomString = fmt.Sprintf(&quot;a%sa\n&quot;, &quot;test&quot;)
    }
	fmt.Printf(&quot;Made 10000 random strings like&quot;, randomString);
}

I've stripped some unrelevant code (as this is obviously not really random).

The issue i'm having is that just under the for-loop, "randomString" is undefined.

I've tried setting it using randomString := fmt.Sprintf() and with the var you've seen above.

I'm quite sure this is a scoping issue (the randomString variable is not in the scope outside of the for-loop), but as a PHP / JS developer, i'm not used to this and would say that variable is also available after the for loop.

How can I access that variable from that point? Basically just displaying the last generated string.

答案1

得分: 10

请参考规范中的相关部分:声明和作用域

在函数内部声明的常量或变量标识符的作用域从 ConstSpec 或 VarSpec(对于短变量声明为 ShortVarDecl)的结束开始,直到最内层包含块的结束

在你希望访问它的作用域中进行定义:在 for 之前(在 main() 函数的作用域中)。

还要注意,fmt.Sprintf() 除了要打印的参数之外,还需要一个额外的参数:格式化字符串。你可以提供一个格式化字符串(例如,为 randomString 参数包含一个 %s 占位符),或者你可以使用 fmt.Sprintln()

func main() {
    var randomString string
    for i := 0; i < 10000; i++ {
        randomString = fmt.Sprintf("a%sa\n", "test")
    }
    fmt.Println("Made 10000 random strings like", randomString)
}

输出:

Made 10000 random strings like atesta

Go Playground 上尝试一下。

英文:

See the relevant section from the spec: Declarations and scope:

> The scope of a constant or variable identifier declared inside a function begins at the end of the ConstSpec or VarSpec (ShortVarDecl for short variable declarations) and ends at the end of the innermost containing block.

Define it in the scope in which you want to access it: before the for (in the scope of the main() function).

Also note that fmt.Sprintf() requires an additional parameter besides the ones to be printed: a format string. Either provide a format string (e.g. include a %s verb for the randomString parameter) or alternatively you may use fmt.Sprintln().

func main() {
	var randomString string
	for i := 0; i &lt; 10000; i++ {
		randomString = fmt.Sprintf(&quot;a%sa\n&quot;, &quot;test&quot;)
	}
	fmt.Println(&quot;Made 10000 random strings like&quot;, randomString)
}

Output:

Made 10000 random strings like atesta

Try it on the Go Playground.

答案2

得分: 2

这是一个作用域问题,在Go语言中,randomString的作用域是循环体,在JavaScript中,它将是整个函数。不同语言的作用域规则是不同的。

请查看Go语言规范:

https://golang.org/ref/spec#Declarations_and_scope

英文:

This is scoping issue, in Go the scope of randomString is the loop body, in JS it would be the whole function. Scoping rules differ in the different languages.

Check the Go spec:

https://golang.org/ref/spec#Declarations_and_scope

huangapple
  • 本文由 发表于 2015年11月20日 17:30:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/33823209.html
匿名

发表评论

匿名网友

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

确定