Golang is statically typed: the compiler needs to know the types of all variables during compilation.
Go can either infer the type, or the developer can explicitly tell the compiler what the type is when declaring variables.
Inferred Type | Explicit Type | |
---|---|---|
Declaration | impossible | var x int |
Declaration and assignment | var x = 4 or x := 4 |
var x int = 4 |
Assignment | x = 4 (inferred from declaration) |
impossible |
The last row, assignment, can only be done after the variable has been declared:
var x int // declare
x = 4 // assign
var y int = 5 // declare and assign
y = 6 // assign
z := 7 // declare and assign
z = 8 // assign
e = 1 // undefined: e
What is the value of a variable when you have declared but not assigned?
Exercise: Discover the zero values of int
, float64
, bool
and string
by writing a go program
Tips:
- You will want to declare but not assign variables.
- You can use
fmt.Println
to see the values.
Similar to import
, there is a shorthand to declare multiple variables:
var (
x int
y string = "hello"
z float64 = 2.1
)
To declare constants, you can use the keyword const
:
const x = 4
const y float64 = 4
const (
a = "hello"
b = "hello"
c = "hello"
)
One difference between const and var: expressions are implicitly repeated in a parenthesized const declaration
const (
a = "hello"
b
c
)
iota
represents successive integer constants 0, 1, 2 ... and is reset after every occurrence of the const
keyword.
const (
zero = 0
one = 1
two = 2
)
can be written as
const (
zero = iota
one
two
)
You can also take advantage of iota
in more complex expressions:
const (
one = iota + 1
two
three
)
Finally, you can skip iota values with _
const (
one = iota + 1
_
three
)
Variables and constants can be declared at the package level, or the block level (between {
and }
, often the function block).
package main
import "fmt"
var (
a int = 4
)
func main() {
b := 5
{
c := 6
fmt.Println(b)
fmt.Println(c)
}
printA()
}
func printA() {
fmt.Println(a)
}
Variables from outer blocks are accessible in inner blocks, but not the other way around. For example, after the inner block that declares c
exits, you will no longer be able to use c
.
When variables are declared at the package level, you can capitalize them to make them exported variables:
// pkg/example/num.go
package example
var (
Big int = 1<<100 // bitshift operator
small int = 0
)
// main.go
package main
import (
"github.com/user/project/pkg/example"
"fmt"
)
func main() {
fmt.Println(example.Big)
fmt.Println(example.small) // breaks
}
Complete the zero-value exercise from above.
- Because the package
main
is never a shared library, it is not appropriate to create any exported resources in this package.
Some general principles on naming.