How to Create a Variable in Go

To create a variable in Golang, you can use the var” keyword or the “short variable declaration syntax with :=”. For example, var name [type] = expression. The type or the expression may be skipped, but not both simultaneously; otherwise, it will throw an error.

package main

import (
  "fmt"
)

func main() {
  var barry int = 21
  var mindy bool = true
  fmt.Println(barry)
  fmt.Println(mindy)
}

Output

21
true

You can see that we created two variables inside the main() functions. One is an integer type, and another is a boolean type. Using the fmt.Println() function, we printed both variables’ values to the console.

The “short variable declaration syntax (:=)” is the most concise and commonly used method for creating and initializing variables in Go, especially within functions. However, it’s important to note that the short variable declaration syntax can only be used inside functions. For package-level variables, you have to use the var keyword.

Leave a Comment