Declaring variables
package main
import "fmt"
func main() {
var name string = "Asha"
var age int = 20
city := "Karad" // short declaration (inside functions)
price, qty := 99.5, 3
fmt.Println(name, age, city, price*float64(qty))
}vardeclares a variable with an optional type.:=declares and infers the type. It only works inside functions.- Unused variables and imports are compile errors in Go.
Basic types
| Type | Example |
|---|---|
int, int64 | 42 |
float64 | 3.14 |
string | "hello" |
bool | true |
rune | 'a' |
byte | 255 |
Zero values
Variables without a value get a default:
var n int // 0
var s string // ""
var b bool // falseConstants
const Pi = 3.14159
const (
Monday = iota // 0
Tuesday // 1
Wednesday // 2
)Type conversion
Go never converts types silently. You must be explicit.
x := 10
y := float64(x) / 3
s := fmt.Sprintf("%d items", x)Formatting output
fmt.Printf("Name: %s, Age: %d, Score: %.2f\n", "Asha", 20, 88.456)Common verbs: %s string, %d integer, %f float, %v any value in default format, %T the type and %q a quoted string.
Multiple assignment and the blank identifier
a, b := 1, 2
a, b = b, a // swap without a temporary variable
_, err := fmt.Println("hi") // _ discards a value you do not needGo forces you to use every variable you declare. The blank identifier _ is how you deliberately ignore a value.
Scope and shadowing
A variable lives inside the nearest pair of braces.
x := 10
if true {
x := 20 // a new variable that shadows the outer x
fmt.Println(x) // 20
}
fmt.Println(x) // 10Shadowing is legal but can hide bugs, so use it carefully and prefer different names.
Package-level variables
Variables declared outside functions are visible to the whole package. Declare them with var, because := only works inside functions.
var appName = "LaunchCV"
func main() {
fmt.Println(appName)
}Practice
Declare variables for a student's name, three marks and compute the average as a float. Print it with two decimals.