2022-12-03

This commit is contained in:
2022-12-03 18:29:02 +00:00
parent f559e0dc2a
commit ccbb0b2294
8 changed files with 122 additions and 0 deletions

7
chapter-1/go_command.go Normal file
View File

@@ -0,0 +1,7 @@
package main
import "fmt"
func main() {
fmt.Println("Hello, world!")
}

BIN
chapter-1/hello Executable file

Binary file not shown.

View File

@@ -0,0 +1,12 @@
package main
import "fmt"
func main() {
var x int = 10
var y float64 = 30.2
var z float64 = float64(x) + y
var d int = x + int(y)
fmt.Println(x, y, z, d)
}

View File

@@ -0,0 +1,19 @@
// can only use := inside functions (this is nearly always used in functions)
// := can re-assign vars, as long as one assignment is new
package main
func main() {
// declaration list
var (
x int
y = 20
z int = 30
d, e = 40, "hello"
f, g string
)
// assign values to existing variables
a := 10
a, b := 20, "hello"
}

33
chapter-2/03_const.go Normal file
View File

@@ -0,0 +1,33 @@
// constants are used to give names to literals
// There is no way to declare that a value is immutable
// Use constants for hard-coded package level variables
// constants can be typed or untyped
// leave them untyped for flexibility (can use an untyped int constant in a func that takes a float etc)
// or hardcode them if needed
package main
import "fmt"
const x int = 10
const (
idKey = "id"
nameKey = "name"
)
const z = 20 * 10
func main() {
const y = "hello"
fmt.Println(x)
fmt.Println(y)
x = x + 1
y = "bye"
fmt.Println(x)
fmt.Println(y)
}

View File

@@ -0,0 +1,18 @@
// variables must be read at least once
// golangci-lint will warn but the compiler will allow it
// package level vars do not need to be read (another reason not to use them)
// constants do not need to be read, if they are not used they are excluded from the build
package main
import "fmt"
func main() {
x := 10
x = 20
fmt.Println(x)
x = 30
}

View File

@@ -0,0 +1,30 @@
// any unicode letter/number is valid for names in go - don't use them
// snake_case is rarely used, use camelCase
// prefer shorter names, k,v for key,value in for loops etc
// if using single letter var names, you can follow the type. E.g i for int, b for bool
// when naming vars/consts in the package level, favour more descriptive names
// !!! the smaller the scope of the variable, the shorter the name !!!
package main
import "fmt"
func main() {
_0 := 0_0
_ᔜ := 20
π := 3
:= "hello" // Unicode U+FF41
fmt.Println(_0)
fmt.Println(_ᔜ)
fmt.Println(π)
fmt.Println()
= "hello" // Unicode U+FF41
a := "goodbye" // standard lowercase a (Unicode U+0061)
fmt.Println()
fmt.Println(a)
}

3
go.mod Normal file
View File

@@ -0,0 +1,3 @@
module learning_go
go 1.19