Skip to content

Commit

Permalink
code demos for CH9,CH10
Browse files Browse the repository at this point in the history
  • Loading branch information
chaocai committed Mar 11, 2019
1 parent a725a10 commit 54becad
Show file tree
Hide file tree
Showing 3 changed files with 112 additions and 0 deletions.
56 changes: 56 additions & 0 deletions code/ch10/func/func_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package fn_test

import (
"fmt"
"math/rand"
"testing"
"time"
)

func returnMultiValues() (int, int) {
return rand.Intn(10), rand.Intn(20)
}

func timeSpent(inner func(op int) int) func(op int) int {
return func(n int) int {
start := time.Now()
ret := inner(n)
fmt.Println("time spent:", time.Since(start).Seconds())
return ret
}
}

func slowFun(op int) int {
time.Sleep(time.Second * 1)
return op
}

func TestFn(t *testing.T) {
a, _ := returnMultiValues()
t.Log(a)
tsSF := timeSpent(slowFun)
t.Log(tsSF(10))
}

func Sum(ops ...int) int {
ret := 0
for _, op := range ops {
ret += op
}
return ret
}

func TestVarParam(t *testing.T) {
t.Log(Sum(1, 2, 3, 4))
t.Log(Sum(1, 2, 3, 4, 5))
}

func Clear() {
fmt.Println("Clear resources.")
}

func TestDefer(t *testing.T) {
defer Clear()
fmt.Println("Start")
panic("err")
}
24 changes: 24 additions & 0 deletions code/ch9/string/string_fun_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package string_test

import (
"strconv"
"strings"
"testing"
)

func TestStringFn(t *testing.T) {
s := "A,B,C"
parts := strings.Split(s, ",")
for _, part := range parts {
t.Log(part)
}
t.Log(strings.Join(parts, "-"))
}

func TestConv(t *testing.T) {
s := strconv.Itoa(10)
t.Log("str" + s)
if i, err := strconv.Atoi("10"); err == nil {
t.Log(10 + i)
}
}
32 changes: 32 additions & 0 deletions code/ch9/string/string_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package string_test

import (
"testing"
)

func TestString(t *testing.T) {
var s string
t.Log(s) //初始化为默认零值“”
s = "hello"
t.Log(len(s))
//s[1] = '3' //string是不可变的byte slice
//s = "\xE4\xB8\xA5" //可以存储任何二进制数据
s = "\xE4\xBA\xBB\xFF"
t.Log(s)
t.Log(len(s))
s = "中"
t.Log(len(s)) //是byte数

c := []rune(s)
t.Log(len(c))
// t.Log("rune size:", unsafe.Sizeof(c[0]))
t.Logf("中 unicode %x", c[0])
t.Logf("中 UTF8 %x", s)
}

func TestStringToRune(t *testing.T) {
s := "中华人民共和国"
for _, c := range s {
t.Logf("%[1]c %[1]x", c)
}
}

0 comments on commit 54becad

Please sign in to comment.