Golang / GoLang Basics Interview Questions
What are the different ways to declare variables in Go?
Go offers several declaration styles. The choice between them is mostly about context (package level vs inside a function) and verbosity. Every variable is always initialised — Go has no uninitialized variables.
| Style | Where usable | Type required? | Notes |
|---|---|---|---|
| var name type | Anywhere | Yes | Initialised to zero value |
| var name = value | Anywhere | No — inferred | Useful when type is obvious from value |
| name := value | Functions only | No — inferred | Most common inside functions |
| var (name type; ...) | Anywhere | Yes | Groups multiple declarations |
// Package-level: var keyword required var appName string = "MyApp" var maxRetries = 3 // type inferred as int // Function-level: short declaration preferred func main() { greeting := "Hello" // most common â := infers type x, y := 10, 20 // multiple assignment x, y = y, x // swap without temp variable! // Blank identifier: discard unwanted values result, _ := divide(10, 3) // ignore the error // var block for related declarations var ( firstName = "Alice" lastName = "Smith" age = 30 ) fmt.Println(greeting, result, firstName, lastName, age) } // Zero values â every variable gets one var i int // 0 var f float64 // 0.0 var b bool // false var s string // ""
More Related questions...