英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论