Declaring variables in Go without specifying type

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

Declaring variables in Go without specifying type

问题

在Go语言中,变量声明后面跟着所期望的类型,例如var x string = "I am a string",但是我正在使用Atom文本编辑器和go-plus插件,go-plus建议我“应该省略变量x的类型声明,因为它可以从右侧推断出来”。所以基本上,即使不指定x的类型,代码仍然可以编译通过?那么在Go语言中指定变量类型是不必要的吗?

英文:

In Go variable declarations are followed by the intended type, for example var x string = "I am a string", but I am using Atom text editor with the go-plus plugin and go-plus suggests that I "should omit type string from declaration of var x; it will be inferred from the right-hand side". So basically, the code still compiles without specifying x's type? So is it unnecessary to specify variable types in Go?

答案1

得分: 11

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

只需要在声明变量时指定类型,而不需要为变量赋值,或者如果你想要的类型与推断的类型不同。否则,变量的类型将与赋值的右侧相同。

// s 和 t 是字符串
s := "this is a string"
// 这种形式在函数体内部不需要,但是效果相同。
var t = "this is another string"

// x 是 *big.Int 类型
x := big.NewInt(0)

// e 是一个空的 error 接口
// 我们指定了类型,因为没有赋值
var e error

// resp 是 *http.Response 类型,err 是 error 类型
resp, err := http.Get("http://example.com")

在全局范围的函数体外部,不能使用:=,但是相同的类型推断仍然适用

var s = "this is still a string"

最后一种情况是当你希望变量具有与推断类型不同的类型时。

// 我们希望 x 是 uint64 类型,即使字面量会被推断为 int
var x uint64 = 3
// 虽然我们可以使用类型转换来实现相同的效果
x := uint64(3)

// 从 http 包中获取,我们希望 DefaultTransport 是一个包含 Transport 的 RoundTripper 接口
var DefaultTransport RoundTripper = &Transport{
...
}

英文:

The important part is "will be inferred from the right-hand side" [of the assignment].

You only need to specify a type when declaring but not assigning a variable, or if you want the type to be different than what's inferred. Otherwise, the variable's type will be the same as that of the right-hand side of the assignment.

// 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")

Outside of a function body at the global scope, you can't use :=, but the same type inference still applies

var s = "this is still a string"

The last case is where you want the variable to have a different type than what's inferred.

// 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{
    ...
}

huangapple
  • 本文由 发表于 2016年1月22日 00:39:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/34929344.html
匿名

发表评论

匿名网友

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

确定