For & Structs - Go Intro (I)

For loops

The most basic for loop with a single condition

1
2
3
4
5
i := 1
for i <= 3 {
fmt.Println(i)
i = i + 1
}

A classic initial/condition/after for loop.

1
2
3
for j := 7; j <= 9; j++ {
fmt.Println(j)
}

A for without a condition will loop repeatedly until you break out of the loop or return from the enclosing function, basically a while loop

1
2
3
4
for {
fmt.Println("loop")
break
}

You can also continue to the next iteration of the loop

1
2
3
4
5
6
for n := 0; n <= 5; n++ {
if n%2 == 0 {
continue
}
fmt.Println(n)
}

For loops in slices. (Basically a for each with indexes :)

1
2
3
for index,value := range sliceName {
fmt.Println("Index: ". index, "Value: ", value)
}

Not classes, structs.

Go is clearly not an object oriented programing language but taking a POO approach to understand Go worked for me.

Struct

A data structure in Go that we can think like a collection of properties that somehow are related together. We can think a struct like a plain object.

Defining a struct in Go that represents a person

1
2
3
4
5
type person struct { 
firstName string
lastName string
age int
}

As you can see we defined a new type person. Then we would be able to create diferent variables of type person like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func main() {
// Option 1
lucas := person{"Lucas", "Contreras",105}
// Option 2
lucas := person{
firstName: "Lucas",
age: 105, lastName: "Contreras",
}
// Option 3
var lucas person // This assigns "Zero values" to the properties depending on this type
lucas.firstName = "Lucas"
lucas.lastName = "Contreras"
lucas.age = 105
}

Different ways of printing a struct

1
2
3
import fmt
fmt.Println(lucas) // Prints the struct within {}
fmt.Printf("%+v", lucas) // This will print the properties { firstName:Lucas lastName:Contreras age:105 }

Nesting sturcts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
type contactInfo struct { 
number int
email string
}

type person struct {
name string
age int
contact contactInfo
// we can omit the "contact" but the property will also bename contactInfo (same as the type)
}

contre := person{
name : "Lucas Contreras",
age: 100,
contact contactInfo{
email: "[email protected]",
number: 123123123123,
} // returns a reference

contre2 := new(Person) // returns a pointer
}

Note that all of the properties of a struct takes a comma at the end of the line regardless if it is the last properties (unlike JSONs)

For: https://github.com/contre95/notes/blob/master/Digitales/Apuntes/Coding/Go/3-For.md
Structs: https://github.com/contre95/notes/blob/master/Digitales/Apuntes/Coding/Go/4-Structs.md


Author: Lucas Contreras