what are package variables in golang declared without a type

Viewed 43

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 Answers

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
Related