Packages, Variables, Functions
Packages, Variables, Functions
Packages
Every Go program is made up of packages and programs start running in the main
package.
Exports
A name, a function or a variable is exported from a package if it begins with a capital letter. When importing a package, you can only refer to its exported names.
Functions
Functions can take one or more arguments and the variable type comes after the name.
func add(x int, y int) int {
return x + y
}
You can also omit the type if the two variables have the same type.
func add(x, y int) int {
return x + y
}
A function can also return multiple results.
func swap(x, y string) (string, string) {
return y, x
}
Go can have something called a "naked" return. This is where the return values are named at the top of the function. If no value is given to the return, it will return the named variables.
func example(x int) (y int) {
y = 0
return // this would return y
}
Variables
var
is used to declare variables and like functions, can be packaged types and the type comes last. You can also give variables a value. If you give it a value, the type can be omitted.
var a, b bool // no value
var a, b = 1, 2 // value
Short variable declarations can be made using :=
. This is to make a variable declaration with implicit type and thus the var
keyword can be omitted. This cannot be used outside a function and therefore variables declared at global scope must have the var
keyword.
Basic Types
bool // boolean
string // string
int // can have 8-32 bit integers. The regular `int` depends on the system architecture (32 vs 64)
byte // 8 bit integer
float32, float64 // float type with 32 and 64 bits
The zero values in Go are 0
, false
, and ""
.
T(v)
converts the variable v
into type T
.
Constants are declared using the const
keyword and cannot be declared using the :=
syntax.