Variables and constants
Context
Section titled “Context”Go provides several ways to declare variables and constants.
Variable declarations
Section titled “Variable declarations”varwith type –var name stringvarwith initializer –var name = "Alice"(type inferred)- Short assignment
:=–name := "Alice"(inside functions only) - Multiple variables –
var x, y int = 1, 2orx, y := 1, 2
Constants
Section titled “Constants”- Declared with
constkeyword. - Cannot be changed after declaration.
- Can be untyped (e.g.,
const Pi = 3.14).
Example
Section titled “Example”Demonstrate different variable declarations and constants.
Code example
Section titled “Code example”package main
import "fmt"
const Pi = 3.14159const ( StatusOK = 200 StatusNotFound = 404)
func main() { var name string = "Alice" var age = 30 city := "Paris" var x, y int = 10, 20 a, b := "hello", true
fmt.Println(name, age, city) fmt.Println(x, y, a, b) fmt.Println(Pi, StatusOK, StatusNotFound)}Output
Section titled “Output”Alice 30 Paris10 20 hello true3.14159 200 404