在Go中声明变量而不指定类型

时间:2016-01-21 16:39:13

标签: go

在Go变量声明之后是预期的类型,例如var x string =“我是一个字符串”,但是我使用带有go-plus插件的Atom文本编辑器和go-plus表明我“应该省略从var x的声明中输入字符串;它将从右侧推断“。所以基本上,代码仍然编译而不指定x的类型?那么在Go中指定变量类型是不必要的吗?

1 个答案:

答案 0 :(得分:5)

重要的部分是“[将从右侧推断] [作业]。

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

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