Browse Source

Add more exercices & activities of chapter 01

master
T. Meissner 4 years ago
parent
commit
07cbe9ece0
4 changed files with 129 additions and 0 deletions
  1. +20
    -0
      chapter_01/activity_1.02/main.go
  2. +30
    -0
      chapter_01/exercise_1.14/main.go
  3. +28
    -0
      chapter_01/exercise_1.15/main.go
  4. +51
    -0
      chapter_01/exercise_1.16/main.go

+ 20
- 0
chapter_01/activity_1.02/main.go View File

@ -0,0 +1,20 @@
package main
import "fmt"
func main() {
a, b := 5, 10
swap(&a, &b)
fmt.Println(a == 10, b == 5)
}
func swap(a *int, b *int) {
// temp := a
// *a, *b = *b, *temp
*a, *b = *b, *a
}

+ 30
- 0
chapter_01/exercise_1.14/main.go View File

@ -0,0 +1,30 @@
package main
import (
"fmt"
"time"
)
func main() {
var count1 *int
count2 := new(int)
countTemp := 5
count3 := &countTemp
t := &time.Time{}
if count1 != nil {
fmt.Printf("count1: %#v\n", *count1)
}
if count2 != nil {
fmt.Printf("count2: %#v\n", *count2)
}
if count3 != nil {
fmt.Printf("count3: %#v\n", *count3)
}
if t != nil {
fmt.Printf("time: %#v\n", *t)
fmt.Printf("time: %#v\n", t.String())
}
}

+ 28
- 0
chapter_01/exercise_1.15/main.go View File

@ -0,0 +1,28 @@
package main
import "fmt"
func add5Value(count int) {
count += 5
fmt.Println("add5Value :", count)
}
func add5Point(count *int) {
*count += 5
fmt.Println("add5Point :", *count)
}
func main() {
var count int
add5Value(count)
fmt.Println("add5Value post:", count)
add5Point(&count)
fmt.Println("add5Point post:", count)
}

+ 51
- 0
chapter_01/exercise_1.16/main.go View File

@ -0,0 +1,51 @@
package main
import "fmt"
const GlobalLimit = 100
const MaxCacheSize = 10 * GlobalLimit
const (
CacheKeyBook = "book_"
CacheKeyCD = "cd_"
)
var cache map[string]string
func cacheGet(key string) string {
return cache[key]
}
func cacheSet(key, val string) {
if len(cache)+1 >= MaxCacheSize {
return
}
cache[key] = val
}
func getBook(isbn string) string {
return cacheGet(CacheKeyBook + isbn)
}
func setBook(isbn, name string) {
cacheSet(CacheKeyBook+isbn, name)
}
func getCD(sku string) string {
return cacheGet(CacheKeyCD + sku)
}
func setCD(sku, title string) {
cacheSet(CacheKeyCD+sku, title)
}
func main() {
cache = make(map[string]string)
setBook("1234-5678", "Get ready to Go")
setCD("1234-5678", "Get ready to Go audio book")
fmt.Println("Book:", getBook("1234-5678"))
fmt.Println("CD :", getCD("1234-5678"))
}

Loading…
Cancel
Save