go - 在 Go 编程语言中定义一个变量

标签 go

我正在学习 Go 语言并遇到这种类型的变量声明:

i:=1;

但是它说 Go 有静态变量。 i,e 变量应该以这样的方式定义

var i int=1;

那么这两种方式有什么区别呢?在第一个中,我们不需要指明数据类型。为什么会这样?

最佳答案

第一个 i := 1 叫做 short variable declaration .它是常规 variable declaration 的简写带有初始化表达式但没有类型:

var IdentifierList = ExpressionList

您没有指定i 的类型,但i 将具有基于特定规则的类型。它的类型将被自动推断。在这种情况下,它将是 int 类型,因为初始化表达式 1 是一个无类型的整数常量,其默认类型为 int,因此当一个类型是必需的(例如,它用于简短的变量声明),将推导 int 类型。

所以 Go 是静态类型的。这意味着变量将具有静态类型,并且在运行时存储在其中的值将始终是该类型。静态类型并不意味着必须明确指定静态类型,它只是意味着变量必须有一个静态类型——在编译时决定——即使你使用短变量声明并且你不要指定它。

请注意,如果使用 var 关键字声明变量,也可以省略类型:

var i = 1

在这种情况下,类型也将从初始化表达式的类型推导出来。

Spec: Variable declaration:

If a type is present, each variable is given that type. Otherwise, each variable is given the type of the corresponding initialization value in the assignment. If that value is an untyped constant, it is first converted to its default type; if it is an untyped boolean value, it is first converted to type bool. The predeclared value nil cannot be used to initialize a variable with no explicit type.

关于go - 在 Go 编程语言中定义一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36278121/

相关文章:

go - goland 重新格式化快捷方式(ctrl+alt+L) 和 go fmt 有什么区别?

go - 如何使用单个 json.Unmarshal 解码字节数组的一部分?

Go Lang-将结构附加到 slice

php - Golang - 有 bcadd/bcsub 包吗?

go - 在其他程序包中初始化并调用struct时,是否可能仅返回一个字段?

string - 问:go-jira: slice 未在模板中 slice 字符串

function - 语法错误 : Non-declaration statement outside function body

google-app-engine - 错误 : (gcloud. app.deploy) INVALID_ARGUMENT:无法解析源

json - 具有未知键的 Unmarshall JSON 上的空结构

go - 你能让 Golang 在写入时丢弃数据包而不是阻塞吗?