package main import fmt strconv our user struct just new data type com

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"fmt"
"strconv"
)
//our user struct
//just a new data type, comprised of both a number and a string
//access the feilds using .level or .nickname
type tUser struct {
level int
nickname string
}
//this is a "method" attached to the struct
//similar to a function
func (user *tUser) levelup() {
fmt.Println(user.nickname + " leveled up!")
user.level = add(user.level, 1)
}
var users = map[string]tUser{
"sobe": {
level: 2,
nickname: "sob",
},
"torp": {
level: 4,
nickname: "torpychan",
},
}
//new "slice" with initial values
//mynums[0] = 5, mynums[1] = 12, mynums[2] = 12
//a slice is like an array, but without a fixed size
var mynums = []int{5, 6, 12}
//this is an array, and cannot be appended to.
var mynumsarray = [3]int{5, 6, 12}
func hi() {
fmt.Println("hi")
}
func add(a int, b int) int {
return a + b
}
func main() {
hi()
/*
A function called after the "defer" keyword
will be activated after the function it is
called from returns.
This one prints a line after main() is
finished.
*/
defer fmt.Println("goodbye :(")
/*
the append() function takes in a slice and a
value to be added onto the end of it.
*/
mynums = append(mynums, 7)
total := 0
for num := range mynums {
total += num
}
fmt.Println("total:", strconv.Itoa(total))
//name is the key, user is the value
for name, user := range users {
//for each element in the map, do this
if name == "sobe" {
user.levelup()
}
//string() returns the UTF-8 (similar to ASCII) equivalent of the number input
//strconv.Itoa() is used, as it prints the numbers... as numbers
//fmt.Println(a,b) is equivalent to fmt.Println(a + " " + b)
fmt.Println(name+", level: "+strconv.Itoa(user.level), "nickname: "+user.nickname)
}
//main() returns
}