1
0
Fork 0

add code comments

main^2
Sebastian Steger 2026-03-24 13:01:43 +00:00
parent 7160d21cdc
commit 60893de6b1
13 changed files with 187 additions and 75 deletions

View File

@ -4,11 +4,14 @@ import "fmt"
func main() { func main() {
//string values and concatenation operator
fmt.Println("go" + "lang") fmt.Println("go" + "lang")
//numeric values and arithmetic operators
fmt.Println("1+1 =", 1+1) fmt.Println("1+1 =", 1+1)
fmt.Println("7.0/3.0 =", 7.0/3.0) fmt.Println("7.0/3.0 =", 7.0/3.0)
//boolean values and logical operators
fmt.Println(true && false) fmt.Println(true && false)
fmt.Println(true || false) fmt.Println(true || false)
fmt.Println(!true) fmt.Println(!true)

View File

@ -4,18 +4,23 @@ import "fmt"
func main() { func main() {
//definition of a single variable
var a = "initial" var a = "initial"
fmt.Println(a) fmt.Println(a)
//definition of multiple variables
var b, c int = 1, 2 var b, c int = 1, 2
fmt.Println(b, c) fmt.Println(b, c)
//definition of multiple variables with implicit type
var d = true var d = true
fmt.Println(d) fmt.Println(d)
//definition of a variable without an initial value, it will be assigned the zero value of its type
var e int var e int
fmt.Println(e) fmt.Println(e)
//definition of a variable with the short declaration operator, it can only be used inside functions
f := "apple" f := "apple"
fmt.Println(f) fmt.Println(f)
} }

View File

@ -1,21 +1,29 @@
package main package main
import ( import (
"fmt" "fmt"
"math" "math"
) )
// Constants are declared like variables, but with the const keyword.
const s string = "constant" const s string = "constant"
func main() { func main() {
fmt.Println(s) //A constant is a simple unchanging value. Constants can be character, string, boolean, or numeric values.
fmt.Println(s)
const n = 500000000 //Constants can be declared as a group, like variables.
const n = 500000000
const d = 3e20 / n //Constant expressions perform arithmetic with arbitrary precision.
fmt.Println(d) const d = 3e20 / n
fmt.Println(d)
fmt.Println(int64(d)) // A numeric constant has no type until it's given one, such as by an explicit cast.
fmt.Println(int64(d))
fmt.Println(math.Sin(n)) // A number can be given a type by using it in a context that requires one,
} // such as a variable assignment or an argument to a function.
// Here, math.Sin expects a float64, so the untyped constant n is given that type.
fmt.Println(math.Sin(n))
}

View File

@ -4,29 +4,39 @@ import "fmt"
func main() { func main() {
i := 1 // For is the only loop statement in Go. No parentheses are needed around the condition,
for i <= 3 { // but the curly braces are required.
fmt.Println(i)
i = i + 1
}
for j := 0; j < 3; j++ { i := 1
fmt.Println(j) // The most basic type, with a single condition.
} for i <= 3 {
fmt.Println(i)
i = i + 1
}
for i := range 3 { // Like in C, the first and third components of the for statement are optional.
fmt.Println("range", i) for j := 0; j < 3; j++ {
} fmt.Println(j)
}
for { // The range form of the for loop iterates over a slice or map.
fmt.Println("loop") for i := range 3 {
break fmt.Println("range", i)
} }
for n := range 6 { // Infinite loops are formed by omitting the loop condition; the loop will repeat
if n%2 == 0 { // until you break out of it or return from the enclosing function.
continue for {
} fmt.Println("loop")
fmt.Println(n) break
} }
// The range form of the for loop can also be used with arrays, slices, maps, and strings.
for n := range 6 {
if n%2 == 0 {
// Skip even numbers.
continue
}
fmt.Println(n)
}
} }

View File

@ -4,25 +4,28 @@ import "fmt"
func main() { func main() {
if 7%2 == 0 { // The if statement is straightforward.
fmt.Println("7 is even") if 7%2 == 0 {
} else { fmt.Println("7 is even")
fmt.Println("7 is odd") } else {
} fmt.Println("7 is odd")
}
if 8%4 == 0 { // You can have an if statement without an else, and the else is optional.
fmt.Println("8 is divisible by 4") if 8%4 == 0 {
} fmt.Println("8 is divisible by 4")
}
if 8%2 == 0 || 7%2 == 0 { if 8%2 == 0 || 7%2 == 0 {
fmt.Println("either 8 or 7 are even") fmt.Println("either 8 or 7 are even")
} }
if num := 9; num < 0 { // A statement can precede conditionals; any variables declared in this statement are available in all branches.
fmt.Println(num, "is negative") if num := 9; num < 0 {
} else if num < 10 { fmt.Println(num, "is negative")
fmt.Println(num, "has 1 digit") } else if num < 10 {
} else { fmt.Println(num, "has 1 digit")
fmt.Println(num, "has multiple digits") } else {
} fmt.Println(num, "has multiple digits")
}
} }

View File

@ -7,11 +7,14 @@ import (
func main() { func main() {
// The switch statement is like a multi-way if. It runs the first case whose value is equal to the condition.
i := 2 i := 2
fmt.Print("Write ", i, " as ") fmt.Print("Write ", i, " as ")
switch i { switch i {
case 1: case 1:
fmt.Println("one") fmt.Println("one")
//no fallthrough, so the next case will not be executed
//no break statement needed, unlike in C or Java
case 2: case 2:
fmt.Println("two") fmt.Println("two")
case 3: case 3:
@ -19,6 +22,7 @@ func main() {
} }
switch time.Now().Weekday() { switch time.Now().Weekday() {
// You can use commas to separate multiple expressions in the same case statement.
case time.Saturday, time.Sunday: case time.Saturday, time.Sunday:
fmt.Println("It's the weekend") fmt.Println("It's the weekend")
default: default:
@ -28,11 +32,14 @@ func main() {
t := time.Now() t := time.Now()
switch { switch {
case t.Hour() < 12: case t.Hour() < 12:
// Switch without an expression is an alternate way to express if/else logic.
// Here we use it to show how the current hour falls into the first or second half of the day.
fmt.Println("It's before noon") fmt.Println("It's before noon")
default: default:
fmt.Println("It's after noon") fmt.Println("It's after noon")
} }
// In Go, a type switch is a construct that permits several type assertions in series.
whatAmI := func(i interface{}) { whatAmI := func(i interface{}) {
switch t := i.(type) { switch t := i.(type) {
case bool: case bool:

View File

@ -4,35 +4,46 @@ import "fmt"
func main() { func main() {
var a [5]int // Arrays in Go have a fixed size and a specific type.
fmt.Println("emp:", a) var a [5]int
fmt.Println("emp:", a)
a[4] = 100 // Set and get a value.
fmt.Println("set:", a) a[4] = 100
fmt.Println("get:", a[4]) fmt.Println("set:", a)
fmt.Println("get:", a[4])
fmt.Println("len:", len(a)) // The builtin len returns the length of an array.
fmt.Println("len:", len(a))
b := [5]int{1, 2, 3, 4, 5} // Array literals
fmt.Println("dcl:", b) b := [5]int{1, 2, 3, 4, 5}
fmt.Println("dcl:", b)
b = [...]int{1, 2, 3, 4, 5} // An array literal with [...] can be used to let the compiler count the array elements.
fmt.Println("dcl:", b) b = [...]int{1, 2, 3, 4, 5}
fmt.Println("dcl:", b)
b = [...]int{100, 3: 400, 500} // Array literals with an index can initialize the specified values and any unspecified
fmt.Println("idx:", b) // values will be set to the zero value of the array's element type.
b = [...]int{100, 3: 400, 500}
fmt.Println("idx:", b)
var twoD [2][3]int // Multidimensional arrays
for i := 0; i < 2; i++ { var twoD [2][3]int
for j := 0; j < 3; j++ { for i := 0; i < 2; i++ {
twoD[i][j] = i + j for j := 0; j < 3; j++ {
} twoD[i][j] = i + j
} }
fmt.Println("2d: ", twoD) }
fmt.Println("2d: ", twoD)
twoD = [2][3]int{ // Array literals for multidimensional arrays
{1, 2, 3}, twoD = [2][3]int{
{1, 2, 3}, {1, 2, 3},
} {1, 2, 3},
fmt.Println("2d: ", twoD) // The comma is required here, even though it's the last element.
} // This helps make diffs cleaner when new elements are added.
}
fmt.Println("2d: ", twoD)
}

View File

@ -2,10 +2,12 @@ package main
import "fmt" import "fmt"
// A pointer holds the memory address of a value. The type *T is a pointer to a T value. Its zero value is nil.
func zeroval(ival int) { func zeroval(ival int) {
ival = 0 ival = 0
} }
// To change the actual value that a pointer points to, we need to dereference the pointer.
func zeroptr(iptr *int) { func zeroptr(iptr *int) {
*iptr = 0 *iptr = 0
} }
@ -14,11 +16,14 @@ func main() {
i := 1 i := 1
fmt.Println("initial:", i) fmt.Println("initial:", i)
// zeroval will get a copy of i, so the original i is not affected.
zeroval(i) zeroval(i)
fmt.Println("zeroval:", i) fmt.Println("zeroval:", i)
// zeroptr will get a pointer to i, so it can change the value of i through the pointer.
zeroptr(&i) zeroptr(&i)
fmt.Println("zeroptr:", i) fmt.Println("zeroptr:", i)
// We can also use the & operator to get the pointer of a variable.
fmt.Println("pointer:", &i) fmt.Println("pointer:", &i)
} }

View File

@ -7,12 +7,16 @@ import (
func main() { func main() {
// A slice is a dynamically-sized, flexible view into the elements of an array.
// In practice, slices are much more common than arrays.
var s []string var s []string
fmt.Println("uninit:", s, s == nil, len(s) == 0) fmt.Println("uninit:", s, s == nil, len(s) == 0)
// To create an empty slice with non-zero length, use the built-in make function.
s = make([]string, 3) s = make([]string, 3)
fmt.Println("emp:", s, "len:", len(s), "cap:", cap(s)) fmt.Println("emp:", s, "len:", len(s), "cap:", cap(s))
// Set and get a value.
s[0] = "a" s[0] = "a"
s[1] = "b" s[1] = "b"
s[2] = "c" s[2] = "c"
@ -21,31 +25,41 @@ func main() {
fmt.Println("len:", len(s)) fmt.Println("len:", len(s))
// Slices can be resliced. This does not copy the slice data.
s = append(s, "d") s = append(s, "d")
s = append(s, "e", "f") s = append(s, "e", "f")
fmt.Println("apd:", s) fmt.Println("apd:", s)
// Deep copy a slice. This creates a new slice with the same length and copies the
// elements from the original slice to the new slice.
c := make([]string, len(s)) c := make([]string, len(s))
copy(c, s) copy(c, s)
fmt.Println("cpy:", c) fmt.Println("cpy:", c)
// Slices support a "slice" operator with the syntax slice[low:high].
// This selects a half-open range which includes the first element, but excludes the last one.
l := s[2:5] l := s[2:5]
fmt.Println("sl1:", l) fmt.Println("sl1:", l)
// This slices up to (but excluding) index 5.
l = s[:5] l = s[:5]
fmt.Println("sl2:", l) fmt.Println("sl2:", l)
// This slices from index 2 to the end of the slice.
l = s[2:] l = s[2:]
fmt.Println("sl3:", l) fmt.Println("sl3:", l)
// You can declare and initialize a slice in a single line as well.
t := []string{"g", "h", "i"} t := []string{"g", "h", "i"}
fmt.Println("dcl:", t) fmt.Println("dcl:", t)
// The builtin "slices" package provides a function Equal to compare two slices for equality.
t2 := []string{"g", "h", "i"} t2 := []string{"g", "h", "i"}
if slices.Equal(t, t2) { if slices.Equal(t, t2) {
fmt.Println("t == t2") fmt.Println("t == t2")
} }
// Slices can be composed into multi-dimensional data structures. The length of the inner slices can vary.
twoD := make([][]int, 3) twoD := make([][]int, 3)
for i := 0; i < 3; i++ { for i := 0; i < 3; i++ {
innerLen := i + 1 innerLen := i + 1

View File

@ -7,33 +7,47 @@ import (
func main() { func main() {
m := make(map[string]int) // A map maps keys to values. The zero value of a map is nil. A nil map has no keys, nor can keys be added.
var m map[string]int
// To create a map, use the builtin make function. The make function allocates and
// initializes a hash map data structure and returns a map value that points to it.
m = make(map[string]int)
// Set key/value pairs using typical name[key] = val syntax.
m["k1"] = 7 m["k1"] = 7
m["k2"] = 13 m["k2"] = 13
fmt.Println("map:", m) fmt.Println("map:", m)
// Get a value for a key with name[key].
v1 := m["k1"] v1 := m["k1"]
fmt.Println("v1:", v1) fmt.Println("v1:", v1)
// If the key is not present in the map, the result is the zero value for the map's value type.
v3 := m["k3"] v3 := m["k3"]
fmt.Println("v3:", v3) fmt.Println("v3:", v3)
fmt.Println("len:", len(m)) fmt.Println("len:", len(m))
// The builtin delete removes key/value pairs from a map.
delete(m, "k2") delete(m, "k2")
delete(m, "k2") // Deleting a non-existent key does not cause an error.
fmt.Println("map:", m) fmt.Println("map:", m)
// The builtin "maps" package provides a function Clear to remove all key/value pairs from a map.
clear(m) clear(m)
fmt.Println("map:", m) fmt.Println("map:", m)
// The optional second return value when getting a value from a map indicates if the key was present in the map.
_, prs := m["k2"] _, prs := m["k2"]
fmt.Println("prs:", prs) fmt.Println("prs:", prs)
// Map literals are like struct literals, but the keys are required.
n := map[string]int{"foo": 1, "bar": 2} n := map[string]int{"foo": 1, "bar": 2}
fmt.Println("map:", n) fmt.Println("map:", n)
// The builtin "maps" package provides a function Equal to compare two maps for equality.
n2 := map[string]int{"foo": 1, "bar": 2} n2 := map[string]int{"foo": 1, "bar": 2}
if maps.Equal(n, n2) { if maps.Equal(n, n2) {
fmt.Println("n == n2") fmt.Println("n == n2")

View File

@ -2,8 +2,11 @@ package main
import "fmt" import "fmt"
// Go does not have a native enum type, but you can achieve similar functionality using constants and iota.
type ServerState int type ServerState int
// iota is a special identifier that is reset to 0 whenever the word const appears in the source and
// increments by one after each const specification. It is often used to create enumerated constants.
const ( const (
StateIdle ServerState = iota StateIdle ServerState = iota
StateConnected StateConnected
@ -11,6 +14,7 @@ const (
StateRetrying StateRetrying
) )
// We can use a map to associate the ServerState values with their string representations.
var stateName = map[ServerState]string{ var stateName = map[ServerState]string{
StateIdle: "idle", StateIdle: "idle",
StateConnected: "connected", StateConnected: "connected",
@ -18,6 +22,7 @@ var stateName = map[ServerState]string{
StateRetrying: "retrying", StateRetrying: "retrying",
} }
// By implementing the Stringer interface, we can define how our ServerState values are printed.
func (ss ServerState) String() string { func (ss ServerState) String() string {
return stateName[ss] return stateName[ss]
} }
@ -31,11 +36,11 @@ func main() {
} }
func transition(s ServerState) ServerState { func transition(s ServerState) ServerState {
// A simple state machine that transitions between states based on the current state.
switch s { switch s {
case StateIdle: case StateIdle:
return StateConnected return StateConnected
case StateConnected, StateRetrying: case StateConnected, StateRetrying:
return StateIdle return StateIdle
case StateError: case StateError:
return StateError return StateError

View File

@ -2,19 +2,31 @@ package main
import "fmt" import "fmt"
// Functions are defined with the func keyword, followed by the function name,
// a list of parameters in parentheses, and the return type.
func plus(a int, b int) int { func plus(a int, b int) int {
return a + b return a + b
} }
// Function overloading is not supported in Go, but we can achieve similar functionality
// by using different function names or by using variadic functions.
// func plus(a float64, b float64) float64 { // compile error: function plus redeclared in this block
// return a + b
// }
// A function with multiple parameters of the same type can be shortened by listing the type only once.
func plusPlus(a, b, c int) int { func plusPlus(a, b, c int) int {
return a + b + c return a + b + c
} }
// Named return values are treated as variables defined at the top of the function.
// A return statement without arguments returns the current values of the named return variables.
func plusNamed(a, b int) (result int) { func plusNamed(a, b int) (result int) {
result = a + b result = a + b
return return
} }
// A function can return multiple values. Here we return the sum and a formatted string description of the operation.
func plusDescription(a int, b int) (int, string) { func plusDescription(a int, b int) (int, string) {
result := a + b result := a + b
return result, fmt.Sprintf("%d+%d = %d", a, b, result) return result, fmt.Sprintf("%d+%d = %d", a, b, result)

View File

@ -2,11 +2,15 @@ package main
import "fmt" import "fmt"
// A struct is a collection of fields. It's useful for grouping data together to form records.
type person struct { type person struct {
name string name string
age int age int
} }
// A struct literal is a list of field values enclosed in braces. You can specify field names or just provide values in order.
// Instead of constructors, Go often uses factory functions that return a pointer to a struct.
// This allows for more flexible initialization and can encapsulate any setup logic.
func newPerson(name string) *person { func newPerson(name string) *person {
p := person{name: name} p := person{name: name}
@ -16,25 +20,36 @@ func newPerson(name string) *person {
func main() { func main() {
// Here we create a new person struct using a struct literal. We specify the field values in order without field names.
fmt.Println(person{"Bob", 20}) fmt.Println(person{"Bob", 20})
// We can also specify field names in the struct literal. This way, the order of fields does not matter.
fmt.Println(person{name: "Alice", age: 30}) fmt.Println(person{name: "Alice", age: 30})
// Omitted fields will be set to their zero value. For example, the age field will be set to 0.
fmt.Println(person{name: "Fred"}) fmt.Println(person{name: "Fred"})
// You can also create a struct using the & operator to get a pointer to the struct. This is often more efficient when passing structs around.
fmt.Println(&person{name: "Ann", age: 40}) fmt.Println(&person{name: "Ann", age: 40})
// Using a factory function to create a new person struct. This allows us to encapsulate any initialization logic and return a pointer to the struct.
fmt.Println(newPerson("Jon")) fmt.Println(newPerson("Jon"))
s := person{name: "Sean", age: 50} s := person{name: "Sean", age: 50}
// Struct fields are accessed using a dot.
fmt.Println(s.name) fmt.Println(s.name)
// You can also access fields through a struct pointer.
// The language automatically dereferences the pointer to access the field.
sp := &s sp := &s
fmt.Println(sp.age) fmt.Println(sp.age)
// Struct fields can be modified through a struct pointer as well. The following statement
// also changes the value of s.age because sp and s point to the same struct in memory.
sp.age = 51 sp.age = 51
fmt.Println(sp.age) fmt.Println(sp.age)
// Anonymous struct is a struct without a name. It's useful for grouping data together without having to define a new type.
dog := struct { dog := struct {
name string name string
isGood bool isGood bool