Short variable declarations

Part of Golang Mastery course

~15 min read
Interactive
Hands-on
Beginner-friendly

Short Variable Declarations#

Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.

Outside a function, every statement begins with a keyword (var, func, and so on) and so the := construct is not available.

Example 1: Printing Variable Values#

example.go
package main
 
import string">"fmt"
 
func main() {
a := 10
b := string">"golang"
c := 4.17
d := true
e := string">"Hello"
f := string">`Do you like my hat?`
g := string">'M'
fmt.Printf(string">"%v \n", a)
fmt.Printf(string">"%v \n", b)
fmt.Printf(string">"%v \n", c)
fmt.Printf(string">"%v \n", d)
fmt.Printf(string">"%v \n", e)
fmt.Printf(string">"%v \n", f)
fmt.Printf(string">"%v \n", g)
}
 

Run in Go Playground →

%v is the format verb for printing values in a default format. It will give you the values of variables.

Example 2: Printing Variable Types#

example.go
package main
 
import string">"fmt"
 
func main() {
a := 10
b := string">"golang"
c := 4.17
d := true
e := string">"Hello"
f := string">`Do you like my hat?`
g := string">'M'
 
fmt.Printf(string">"%T \n", a)
fmt.Printf(string">"%T \n", b)
fmt.Printf(string">"%T \n", c)
fmt.Printf(string">"%T \n", d)
fmt.Printf(string">"%T \n", e)
fmt.Printf(string">"%T \n", f)
fmt.Printf(string">"%T \n", g)
}
 

Run in Go Playground →

The %T format verb provides a Go-syntax representation of the type of the value. In this example, it shows the type of each variable.

example.go
package main
 
import string">"fmt"
 
func main() {
 
a := 10
b := string">"golang"
c := 4.17
d := true
e := string">"Hello"
f := string">`Do you like my hat?`
g := string">'M'
 
fmt.Printf(string">"%T \n", a)
fmt.Printf(string">"%T \n", b)
fmt.Printf(string">"%T \n", c)
fmt.Printf(string">"%T \n", d)
fmt.Printf(string">"%T \n", e)
fmt.Printf(string">"%T \n", f)
fmt.Printf(string">"%T \n", g)
}
 

RUN

%T a Go-syntax representation of the type of the value in this above go program %T provide you the type of variable

Your Progress

8 of 103 modules
8%
Started8% Complete
Previous
SpaceComplete
Next