DEV Community

Cover image for [Golang 02/30] Go declare variables
Xun Zhou
Xun Zhou

Posted on

[Golang 02/30] Go declare variables

package main

import (
  "fmt"
)

func main() {
  // declare a variable with value "hello"
  var a = "hello"
  fmt.Printf("\na: %s", a)

  // shortcut for "var ab string"
  // it declares a variable named "ab", 
  // and auto-detect its type and assign the value "hello" to it.
  ab := "hello"
  fmt.Printf("\nab: %s", ab)

  // declare a variable with explicit type
  var abc string= "hello"
  fmt.Printf("\nabc: %s", abc)

  // declare multiple variables with type "int"
  var b, c int;
  fmt.Printf("\nb: %d, c:%d", b, c)

  // declare multiple variables and assign them the values
  // the types will be auto-detected
  var d, e = 1, "golang"
  fmt.Printf("\nd: %d, e: %s", d, e)
}

Enter fullscreen mode Exit fullscreen mode

It prints the following content:

a: hello
ab: hello
abc: hello
b: 0, c:0
d: 1, e: golang
Enter fullscreen mode Exit fullscreen mode

Summary

In Go, we can declare variables using the var keyword or its shortcut :=.
Golang will assign the default value to the variables, which are not initialized.
For example:

  • string default: empty string
  • int default: 0
  • bool default: false

Top comments (0)