go - for循环中的变量在外部未定义

标签 go scope

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

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/

相关文章:

go - 如何构建 mgo 查询?

Golang 如何将网站部署到主机

javascript - $scope 无法在控制台上运行

jquery - 如何使函数内部的变量值更新以在顶级变量上生效

Javascript 无法推送到函数内部的全局数组

javascript - 定义脚本标签执行的范围

go - 如何在 Visual Studio Code 中使用 Cgo 调试 Go

go - Golang 1.8 glide vendor 文件夹忽略

unit-testing - 如何在自定义文件夹中使用 go test 生成多个包的覆盖率?

c++ - 使用运算符重载时,难以在命名空间内分离类的 header /源