我想知道为什么下面这段代码不起作用:
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 循环之后也可用。
我怎样才能从那个点访问那个变量?基本上只是显示最后生成的字符串。
最佳答案
请参阅规范中的相关部分: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.
在您想要访问它的范围内定义它:在 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 上试试.
关于go - for循环中的变量在外部未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33823209/