0

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
  • 3
    See the Tour of Go and the language specification. If the type is not present, then the variable is given the type of corresponding initialization value in the assignment. In the question's example, the initialization value has type *Encoding. Commented Sep 17, 2022 at 23:32

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

thank you for the concise explanation. that helps. My last question is how/when are these variables used? I came across one example here: fmt.Println(base64.StdEncoding.EncodeToString([]byte("user:pass"))) I have a general understanding what is happening here but i had to write this myself, I would be stuck since I dont understand the details of it
if your concern is about how/when to use the variable, I think it like other usecase of variable. the variable used to store the value or instance so you can use it multiple times. But if your concern is more specific to usage of package encoding/base64 honestly I don't have enough knowledge to talk about it.
So I figured usage about the encoding/base64 package. There are 4 ways to encode data and hence there are 4 variables (pkg.go.dev/encoding/base64#pkg-variables).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.