DEV Community

Cover image for Summary of Variable Definitions and Declarations in Golang
Kenta Takeuchi
Kenta Takeuchi

Posted on • Originally published at bmf-tech.com

Summary of Variable Definitions and Declarations in Golang

#go

This article was originally published on bmf-tech.com.

Overview

A summary of patterns for variable definitions and declarations in Golang.

Cautions in Variable Definitions and Declarations

  • If the first letter is uppercase, the variable is visible from other packages.
  • If the first letter is lowercase, the variable is only visible within the package.

Variable Definitions and Declarations

Variable declarations

var i int
fmt.Printf("%T", i) // int
Enter fullscreen mode Exit fullscreen mode
var a, b, c string
fmt.Printf("%T", a) // string
fmt.Printf("%T", b) // string
fmt.Printf("%T", c) // string
Enter fullscreen mode Exit fullscreen mode
var s = "Hello World"
fmt.Printf("%T", s) // string
Enter fullscreen mode Exit fullscreen mode
var x, y, z int = 1, 2, 3
fmt.Printf("%T", x) // int
fmt.Printf("%T", y) // int
fmt.Printf("%T", z) // int
Enter fullscreen mode Exit fullscreen mode
var (
   a string
   x int
   y, z = 2, 3
)
fmt.Printf("%T", a) // string
fmt.Printf("%T", x) // int
fmt.Printf("%T", y) // int
fmt.Printf("%T", z) // int
Enter fullscreen mode Exit fullscreen mode
var i, j = 1, 2
fmt.Printf("%T", i) // int
fmt.Printf("%T", j) // int
Enter fullscreen mode Exit fullscreen mode

Short variable declarations

  • The shorthand variable declaration can only be used within functions.
i := 1
fmt.Printf("%T", i) // int
Enter fullscreen mode Exit fullscreen mode
i, j := 1, 2
fmt.Printf("%T", i) // int
fmt.Printf("%T", j) // int
Enter fullscreen mode Exit fullscreen mode

References

Top comments (0)