go - 在不指定类型的情况下在 Go 中声明变量

标签 go

在 Go 中,变量声明后跟预期的类型,例如 var x string = "I am a string",但我使用带有 go-plus 插件的 Atom 文本编辑器并且 go-plus 建议我“应该省略从 var x 的声明中键入字符串;将从右侧推断出来”。所以基本上,代码仍然可以在不指定 x 类型的情况下编译?那么Go中是不是不需要指定变量类型呢?

最佳答案

重要的部分是“将从右侧推断”[赋值]。

您只需要在声明但不分配变量时指定类型,或者如果您希望类型不同于推断的类型。否则,变量的类型将与赋值右侧的类型相同。

// s and t are strings
s := "this is a string"
// this form isn't needed inside a function body, but works the same.
var t = "this is another string"

// x is a *big.Int
x := big.NewInt(0)

// e is a nil error interface
// we specify the type, because there's no assignment
var e error

// resp is an *http.Response, and err is an error
resp, err := http.Get("http://example.com")

在全局作用域的函数体之外,你不能使用:=,但同样的类型推断仍然适用

var s = "this is still a string"

最后一种情况是您希望变量的类型不同于推断的类型。

// we want x to be an uint64 even though the literal would be 
// inferred as an int
var x uint64 = 3
// though we would do the same with a type conversion 
x := uint64(3)

// Taken from the http package, we want the DefaultTransport 
// to be a RoundTripper interface that contains a Transport
var DefaultTransport RoundTripper = &Transport{
    ...
}

关于go - 在不指定类型的情况下在 Go 中声明变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34929344/

相关文章:

file - 文件在 Windows 上填充了数据,但在 Linux 上没有

mongodb - go.mongodb.org/mongo-driver - InsertOne with NilValueObjectId

json - 在匹配 Go 中的底层类型时将 JSON 解码为接口(interface)变量

go - 使用 golang AddDate 计算日期的正确方法是什么

go - 检查是否可以用给定长度的边构建三角形的程序。如何缩短 IF 条件?

用于谷歌云存储的 Golang SDK : Multipart download

go - 在 Go 中遍历 unicode 字符串时跳过 n 个代码点

golang http 服务器 http.ListenAndServe 仅适用于本地主机?

go - 无法将 !!seq 解码为 Go 中的字符串

Golang Goroutine 内存泄漏