|
| 1 | +package interview |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "time" |
| 7 | +) |
| 8 | + |
| 9 | +func cacl(index string, a, b int) int { |
| 10 | + ret := a + b |
| 11 | + fmt.Println(index, a, b, ret) |
| 12 | + return ret |
| 13 | +} |
| 14 | + |
| 15 | +func DeferAction() { |
| 16 | + a := 1 |
| 17 | + b := 2 |
| 18 | + |
| 19 | + defer cacl("1", a, cacl("10", a, b)) |
| 20 | + |
| 21 | + b = 0 |
| 22 | + defer cacl("2", a, cacl("20", a, b)) |
| 23 | + b = 3 |
| 24 | + |
| 25 | + panic("exit") |
| 26 | + |
| 27 | + // output |
| 28 | + // 10 1 2 3 |
| 29 | + // 20 1 0 1 |
| 30 | + // 2 1 1 2 |
| 31 | + // 1 1 3 4 |
| 32 | + // panic: exit |
| 33 | +} |
| 34 | + |
| 35 | +func CloseChan() { |
| 36 | + type A struct { |
| 37 | + val int |
| 38 | + } |
| 39 | + |
| 40 | + c := make(chan *A, 10) |
| 41 | + |
| 42 | + c <- &A{val: 1} |
| 43 | + c <- &A{val: 2} |
| 44 | + close(c) |
| 45 | + |
| 46 | + for i := range c { |
| 47 | + fmt.Println(i) |
| 48 | + } |
| 49 | + |
| 50 | + fmt.Println(<-c) |
| 51 | + fmt.Println(<-c) |
| 52 | + |
| 53 | + // output |
| 54 | + |
| 55 | + //&{1} |
| 56 | + //&{2} |
| 57 | + //<nil> |
| 58 | + //<nil> |
| 59 | +} |
| 60 | + |
| 61 | +func MapInit() { |
| 62 | + type A struct { |
| 63 | + val int |
| 64 | + } |
| 65 | + |
| 66 | + // 以下用法错误 map的值是无法取址的,也就无法对结构体里的field进行操作; 因为map是无序的,并且随时存在扩容缩容,其地址也就不固定 |
| 67 | + // m := map[string]A{"x": {1}} |
| 68 | + // m["x"].val = 2 |
| 69 | + |
| 70 | + // 解决方案 |
| 71 | + // m := map[string]&A |
| 72 | +} |
| 73 | + |
| 74 | +func ConText() { |
| 75 | + ctx, _ := context.WithCancel(context.Background()) |
| 76 | + //defer cancel() |
| 77 | + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) |
| 78 | + |
| 79 | + resp := make(chan int, 3) |
| 80 | + err := make(chan interface{}, 3) |
| 81 | + |
| 82 | + operation := func(pid int, ctx context.Context, dst int, resp chan int, err chan interface{}) { |
| 83 | + n := 1 |
| 84 | + for { |
| 85 | + select { |
| 86 | + case <-ctx.Done(): |
| 87 | + fmt.Println(pid, "canceled", ctx.Err()) |
| 88 | + err <- ctx.Err() |
| 89 | + return |
| 90 | + case <-time.After(time.Second): |
| 91 | + fmt.Println(pid, "1 second pass", n) |
| 92 | + n++ |
| 93 | + if n == dst { |
| 94 | + resp <- pid |
| 95 | + return |
| 96 | + } |
| 97 | + } |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + go operation(1, ctx, 10, resp, err) |
| 102 | + go operation(2, ctx, 10, resp, err) |
| 103 | + go operation(3, ctx, 7, resp, err) |
| 104 | + |
| 105 | + select { |
| 106 | + case pid := <-resp: |
| 107 | + fmt.Println(pid, "find dst and cancel other goroutines") |
| 108 | + case e := <-err: |
| 109 | + fmt.Println(e) |
| 110 | + } |
| 111 | + |
| 112 | + cancel() |
| 113 | + time.Sleep(1 * time.Second) // wait for goroutines return |
| 114 | +} |
0 commit comments