02-Some Fundamentals
Main topics:
- importing packages
- variable declarions
- short and constant declaration
- zero values
1. Importing packages
- In the previous chapter, we used a package "import fmt".
-
In Go, a package is a collection of related source files that are compiled together.
For example, the "fmt" package provides functions for formatted input and output, such as fmt.Println() and fmt.Printf().
-
In Go, a program must import a package at the beginning of the source file to access and use the functionality defined in that package.
An example
2. Declaring Variables
Syntax to create a variable is
For example,
3. Built-in data types
Basic types
- bool
- string
Integer types
- int
- int8
- int16
- int32 (alias: rune)
- int64
- uint
- uint8 (alias: byte)
- uint16
- uint32
- uint64
- uintptr
Float types
- float32
- float64
Complex types
- complex64
- complex128
Alias types
- byte (alias for uint8)
- rune (alias for int32)
4. Short variable declaration
- The short variable declaration syntax uses := to declare and initialize a variable in one concise statement.
- It automatically infers the variable’s type from the value on the right-hand side. -It can only be used inside functions (not at the package level).
Syntax
Important points about short variable declation
- Variable type is inferred automatically.
- You cannot use := without initialization (no zero value-only declarations).
- Very handy for quick and readable code inside functions.
- You cannot declare a variable without initialization
We can change the value of the variable, but then we have to use "=" instead of ":="
func main() {
x := 10 // Declare and initialize x with 10
fmt.Println(x) // Output: 10
//x :=20 COMPILATION ERROR
x = 20 // Reassign a new value to x
fmt.Println(x) // Output: 20
}
'short declaration' outside functions not allowed
- You cannot do this at the package level (outside functions)
- At the package level (outside any function), Go requires explicit var declarations at the top level. (This point will be discussed in more details in the section of Packages later.)
'short declaration' summary:
context | allowed |
---|---|
inside functions | YES |
outside function (e.g. package level) | NO |
value update | NO |
5. Constants in Go (Immutables)
The const keyword in Go is used to declare constant values — these are values that cannot change after they're defined.
6. Zero values
In Go, "zero values" are the default values assigned to variables when they are declared but not explicitly initialized.
Type | Zero Value |
---|---|
bool | false |
int, float | 0, 0.0 |
string | empty string (not Nil) |
pointer, func, interface{}, map, slice, chan | Nil |
struct | Fields = zero values |
Note:
- Some of the above data types are not explained in this chapter (such as struct, pointer...). They will be described in the subsequent chapters.
- nil is used with reference types, not value types (to be explained in coming chapters)