Go Q & A

 

What is the syntax for declaring variables in Go?

In Go, variables are declared using the var keyword followed by the variable name, optional type declaration, and initial value. The syntax for declaring variables in Go is as follows:

go

var variableName dataType = initialValue

Alternatively, Go also supports a shorter syntax using type inference, where the type declaration is omitted and the compiler infers the type based on the initial value:

go

var variableName = initialValue

 

If the initial value is provided, Go automatically infers the variable’s type based on the type of the initial value. If the type is not explicitly specified, Go assigns the appropriate type based on the value provided.
For example:

go

var age int = 30

Or, using type inference:

go

var age = 30

Go also allows for short variable declaration using the := operator, which declares and initializes variables within a function body:

go

age := 30

This syntax automatically infers the type of the variable based on the provided initial value.

Previously at
Flag Argentina
Mexico
time icon
GMT-6
Over 5 years of experience in Golang. Led the design and implementation of a distributed system and platform for building conversational chatbots.