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 // ""
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
