go / beginner
Snippet
Variable Declaration and Type Inference
Go allows two ways to declare variables. The `var` keyword with explicit type, or the `:=` short syntax which infers the type from the value. Variables declared with `:=` inside a function are called short variable declarations.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
package mainimport "fmt"func main() {// Explicit type declarationvar name string = "Go"age := 25 // Type inferred as intfmt.Printf("Language: %s, Age: %d\n", name, age)}
Breakdown
1
var name string = "Go"
Explicit declaration with var keyword and type string
2
age := 25
Short declaration where type is inferred as int automatically
3
fmt.Printf(...)
Formatted print using printf with %s for string, %d for int