roundtrip.go raw

   1  package main
   2  
   3  import (
   4  	"fmt"
   5  	"strings"
   6  	"sync"
   7  )
   8  
   9  type Config struct {
  10  	Name    string
  11  	Count   int
  12  	Values  map[string]interface{}
  13  	mu      sync.Mutex
  14  }
  15  
  16  var defaultConfig = &Config{
  17  	Name:  "default",
  18  	Count: 100,
  19  }
  20  
  21  func init() {
  22  	defaultConfig.Values = make(map[string]interface{})
  23  }
  24  
  25  func init() {
  26  	fmt.Println("second init")
  27  }
  28  
  29  func main() {
  30  	cfg := defaultConfig
  31  	cfg.mu.Lock()
  32  	defer cfg.mu.Unlock()
  33  
  34  	ch := make(chan int)
  35  	go func() {
  36  		for i := 0; i < 10; i++ {
  37  			ch <- i * i
  38  		}
  39  		close(ch)
  40  	}()
  41  
  42  	results := make([]int, 0, 20)
  43  	for v := range ch {
  44  		results = append(results, v)
  45  	}
  46  
  47  	msg := "results: " + fmt.Sprint(results)
  48  	fmt.Println(msg)
  49  
  50  	switch v := cfg.Count; {
  51  	case v < 10:
  52  		fmt.Println("small")
  53  	case v < 100:
  54  		fallthrough
  55  	case v < 1000:
  56  		fmt.Println("medium")
  57  	default:
  58  		fmt.Println("large")
  59  	}
  60  
  61  	if s, ok := cfg.Values["key"].(string); ok {
  62  		fmt.Println(strings.ToUpper(s))
  63  	}
  64  
  65  	var total uint
  66  	for _, r := range results {
  67  		total += uint(r)
  68  	}
  69  	fmt.Printf("total: %d\n", total)
  70  }
  71  
  72  func process(data []byte, n int) []byte {
  73  	out := new(bytes.Buffer)
  74  	for i := 0; i < n; i++ {
  75  		out.Write(data)
  76  	}
  77  	return out.Bytes()
  78  }
  79