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
var a, b, c string
fmt.Printf("%T", a) // string
fmt.Printf("%T", b) // string
fmt.Printf("%T", c) // string
var s = "Hello World"
fmt.Printf("%T", s) // string
var x, y, z int = 1, 2, 3
fmt.Printf("%T", x) // int
fmt.Printf("%T", y) // int
fmt.Printf("%T", z) // int
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
var i, j = 1, 2
fmt.Printf("%T", i) // int
fmt.Printf("%T", j) // int
Short variable declarations
- The shorthand variable declaration can only be used within functions.
i := 1
fmt.Printf("%T", i) // int
i, j := 1, 2
fmt.Printf("%T", i) // int
fmt.Printf("%T", j) // int
Top comments (0)