what are package variables in golang declared without a type

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

what are package variables in golang declared without a type

问题

我是新手,对golang和编程都不太熟悉。在阅读golang文档时,我遇到了一些没有与之关联的类型声明的变量。

例如:var StdEncoding = NewEncoding(encodeStd)

我在encode/base64包中看到了这个。我不确定它是什么意思。我知道在声明变量时需要指定类型,但这个变量没有指定任何类型。这些变量与其他变量有什么不同,我该如何使用它们?

英文:

I am new to golang and fairly new to programming. While reading the golang documentation I came across variables declared without type associated to it.

eg: var StdEncoding = NewEncoding(encodeStd)

I can this in the encode/base64 package. I am not sure what it means. I know that you need to mention that type while declaring variables but this one doesnt have any type. How are these variables different from other and how do I use them?

答案1

得分: 1

在Go语言中,我们必须为每个变量指定类型。如果使用var关键字,可以声明一个变量而不给它赋值,但是必须声明变量的类型。

var a int
a = 10

但是,如果使用var关键字声明一个变量并直接给它赋值,你可以选择是否声明类型。如果不声明类型,Go语言将根据赋给变量的值来确定类型。在你的例子中,因为NewEncoding将返回*Encoding类型,所以变量stdEncoding的类型将是Encoding结构体。

var a int = 10 // 你可以这样做
var a = 10 // 也可以这样做
英文:

in golang, we must specify the type for each variable. if you use var keyword you can declare variable without assign the value, but you must declare the type also.

var a int
a = 10

but if you use var keyword to declare a variable and directly assign the value to it, you have option to declare the type or not. if not, golang will decide the type base on the value assigned to variable. In your example because NewEncoding will return *Encoding so type of variable stdEncoding will be Encoding struct.

var a int = 10 // you can do this
var a = 10 // also, you can do this

huangapple
  • 本文由 发表于 2022年9月18日 06:54:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/73759050.html
匿名

发表评论

匿名网友

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

确定