A-D

  1. package main
  2. import "fmt"
  3. func main() {
  4. //创建int型数组a,大小为5,数组内默认值为0
  5. var a [5]int
  6. fmt.Println("emp:", a)
  7. //对int数组a的索引为4的元素赋值为100
  8. a[4] = 100
  9. fmt.Println("set:", a)
  10. fmt.Println("get:", a[4])
  11. //判定长度
  12. fmt.Println("len:", len(a))
  13. //采用短变量声明一个int数组b,并指定相应位置的值
  14. b := [5]int{1, 2, 3, 4, 5}
  15. fmt.Println("dcl:", b)
  16. //与b的创建一样,初始为空数组,大小5
  17. c := [5]int{}
  18. fmt.Println("c:", c)
  19. //创建二维数组 默认为空
  20. var twoD [2][3]int
  21. for i := 0; i < 2; i++ {
  22. for j := 0; j < 3; j++ {
  23. twoD[i][j] = i + j
  24. }
  25. }
  26. fmt.Println("2d: ", twoD)
  27. }
  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. "sync/atomic"
  6. )
  7. func main() {
  8. var ops uint64
  9. var wg sync.WaitGroup
  10. for i := 0; i < 50; i++ {
  11. wg.Add(1)
  12. go func() {
  13. for c := 0; c < 1000; c++ {
  14. atomic.AddUint64(&ops, 1)
  15. }
  16. wg.Done()
  17. }()
  18. }
  19. wg.Wait()
  20. fmt.Println("ops:", ops)
  21. }
  1. package main
  2. import (
  3. b64 "encoding/base64"
  4. "fmt"
  5. )
  6. func main() {
  7. data := "abc123!?$*&()'-=@~"
  8. //对字符串进行
  9. sEnc := b64.StdEncoding.EncodeToString([]byte(data))
  10. fmt.Println(sEnc)
  11. sDec, _ := b64.StdEncoding.DecodeString(sEnc)
  12. fmt.Println(string(sDec))
  13. fmt.Println()
  14. uEnc := b64.URLEncoding.EncodeToString([]byte(data))
  15. fmt.Println(uEnc)
  16. uDec, _ := b64.URLEncoding.DecodeString(uEnc)
  17. fmt.Println(string(uDec))
  18. }
  1. package main
  2. import "fmt"
  3. func main() {
  4. messages := make(chan string, 2)
  5. messages <- "buffered"
  6. messages <- "channel"
  7. fmt.Println(<-messages)
  8. fmt.Println(<-messages)
  9. }
  1. package main
  2. import "fmt"
  3. func ping(pings chan<- string, msg string) {
  4. pings <- msg
  5. }
  6. func pong(pings <-chan string, pongs chan<- string) {
  7. msg := <-pings
  8. pongs <- msg
  9. }
  10. func main() {
  11. pings := make(chan string, 1)
  12. pongs := make(chan string, 1)
  13. ping(pings, "passed message")
  14. pong(pings, pongs)
  15. fmt.Println(<-pongs)
  16. }
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func worker1(done chan bool) {
  7. fmt.Print("working...")
  8. time.Sleep(time.Second)
  9. fmt.Println("done")
  10. done <- true
  11. }
  12. func main() {
  13. done := make(chan bool, 1)
  14. go worker1(done)
  15. //<-done
  16. }
  1. package main
  2. import "fmt"
  3. func main() {
  4. //通道(channels) 是连接多个协程的管道。 你可以从一个协程将值发送到通道,然后在另一个协程中接收。
  5. //使用 make(chan val-type) 创建一个新的通道
  6. messages := make(chan string)
  7. //channel(messages) <- string 发送一个值到通道中
  8. go func() { messages <- "ping" }()
  9. //从通道中 接收一个值
  10. //变量 := <-channel
  11. msg := <-messages
  12. fmt.Println(msg)
  13. }
  1. package main
  2. import "fmt"
  3. func main() {
  4. jobs := make(chan int, 5)
  5. done := make(chan bool)
  6. go func() {
  7. for {
  8. j, more := <-jobs
  9. if more {
  10. fmt.Println("received job", j)
  11. } else {
  12. fmt.Println("received all jobs")
  13. done <- true
  14. return
  15. }
  16. }
  17. }()
  18. for j := 1; j <= 3; j++ {
  19. jobs <- j
  20. fmt.Println("sent job", j)
  21. }
  22. close(jobs)
  23. fmt.Println("sent all jobs")
  24. <-done
  25. }
  1. package main
  2. import "fmt"
  3. func intSeq() func() int {
  4. //函数式编程,可以参考《计算机程序构造与解释》一书(Lisp)
  5. i := 0 //----1
  6. return func() int {
  7. i++ //----2
  8. return i //----3
  9. }
  10. }
  11. func main() {
  12. nextInt := intSeq()
  13. fmt.Println(nextInt())
  14. fmt.Println(nextInt())
  15. fmt.Println(nextInt())
  16. newInts := intSeq()
  17. fmt.Println(newInts())
  18. }
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. )
  6. func main() {
  7. argsWithProg := os.Args
  8. argsWithoutProg := os.Args[1:]
  9. arg := os.Args[3]
  10. fmt.Println(argsWithProg)
  11. fmt.Println(argsWithoutProg)
  12. fmt.Println(arg)
  13. }
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. )
  6. func main() {
  7. wordPtr := flag.String("word", "foo", "a string")
  8. numbPtr := flag.Int("numb", 42, "an int")
  9. forkPtr := flag.Bool("fork", false, "a bool")
  10. var svar string
  11. flag.StringVar(&svar, "svar", "bar", "a string var")
  12. flag.Parse()
  13. fmt.Println("word:", *wordPtr)
  14. fmt.Println("numb:", *numbPtr)
  15. fmt.Println("fork:", *forkPtr)
  16. fmt.Println("svar:", svar)
  17. fmt.Println("tail:", flag.Args())
  18. }
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "os"
  6. )
  7. func main() {
  8. fooCmd := flag.NewFlagSet("foo", flag.ExitOnError)
  9. fooEnable := fooCmd.Bool("enable", false, "enable")
  10. fooName := fooCmd.String("name", "", "name")
  11. barCmd := flag.NewFlagSet("bar", flag.ExitOnError)
  12. barLevel := barCmd.Int("level", 0, "level")
  13. if len(os.Args) < 2 {
  14. fmt.Println("expected 'foo' or 'bar' subcommands")
  15. os.Exit(1)
  16. }
  17. switch os.Args[1] {
  18. case "foo":
  19. fooCmd.Parse(os.Args[2:])
  20. fmt.Println("subcommand 'foo'")
  21. fmt.Println(" enable:", *fooEnable)
  22. fmt.Println(" name:", *fooName)
  23. fmt.Println(" tail:", fooCmd.Args())
  24. case "bar":
  25. barCmd.Parse(os.Args[2:])
  26. fmt.Println("subcommand 'bar'")
  27. fmt.Println(" level:", *barLevel)
  28. fmt.Println(" tail:", barCmd.Args())
  29. default:
  30. fmt.Println("expected 'foo' or 'bar' subcommands")
  31. os.Exit(1)
  32. }
  33. }
  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. const s string = "constant"
  7. //常量不允许修改
  8. func main() {
  9. fmt.Println(s)
  10. const n = 500000000 //5*10^8
  11. const d = 3e20 / n //3*10^20
  12. fmt.Println(d) //0.6*10^12 = 6 * 10^11
  13. fmt.Println(int64(d))
  14. //math.sin需要float64 n会自动确认类型
  15. fmt.Println(math.Sin(n))
  16. }
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "time"
  6. )
  7. func hello1(w http.ResponseWriter, req *http.Request) {
  8. ctx := req.Context()
  9. fmt.Println("server: hello handler started")
  10. defer fmt.Println("server: hello handler ended")
  11. select {
  12. case <-time.After(10 * time.Second):
  13. fmt.Fprintf(w, "hello\n")
  14. case <-ctx.Done():
  15. err := ctx.Err()
  16. fmt.Println("server:", err)
  17. internalError := http.StatusInternalServerError
  18. http.Error(w, err.Error(), internalError)
  19. }
  20. }
  21. func main() {
  22. http.HandleFunc("/hello", hello)
  23. http.ListenAndServe(":8090", nil)
  24. }
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. )
  6. func main() {
  7. f := createFile("/tmp/defer.txt")
  8. defer closeFile(f)
  9. writeFile(f)
  10. }
  11. func createFile(p string) *os.File {
  12. fmt.Println("creating")
  13. f, err := os.Create(p)
  14. if err != nil {
  15. panic(err)
  16. }
  17. return f
  18. }
  19. func writeFile(f *os.File) {
  20. fmt.Println("writing")
  21. fmt.Fprintln(f, "data")
  22. }
  23. func closeFile(f *os.File) {
  24. fmt.Println("closing")
  25. err := f.Close()
  26. if err != nil {
  27. fmt.Fprintf(os.Stderr, "error: %v\n", err)
  28. os.Exit(1)
  29. }
  30. }
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. )
  7. func check2(e error) {
  8. if e != nil {
  9. panic(e)
  10. }
  11. }
  12. func main() {
  13. err := os.Mkdir("subdir", 0755)
  14. check2(err)
  15. defer os.RemoveAll("subdir")
  16. createEmptyFile := func(name string) {
  17. d := []byte("")
  18. check2(os.WriteFile(name, d, 0644))
  19. }
  20. createEmptyFile("subdir/file1")
  21. err = os.MkdirAll("subdir/parent/child", 0755)
  22. check2(err)
  23. createEmptyFile("subdir/parent/file2")
  24. createEmptyFile("subdir/parent/file3")
  25. createEmptyFile("subdir/parent/child/file4")
  26. c, err := os.ReadDir("subdir/parent")
  27. check2(err)
  28. fmt.Println("Listing subdir/parent")
  29. for _, entry := range c {
  30. fmt.Println(" ", entry.Name(), entry.IsDir())
  31. }
  32. err = os.Chdir("subdir/parent/child")
  33. check2(err)
  34. c, err = os.ReadDir(".")
  35. check2(err)
  36. fmt.Println("Listing subdir/parent/child")
  37. for _, entry := range c {
  38. fmt.Println(" ", entry.Name(), entry.IsDir())
  39. }
  40. err = os.Chdir("../../..")
  41. check2(err)
  42. fmt.Println("Visiting subdir")
  43. err = filepath.Walk("subdir", visit)
  44. }
  45. func visit(p string, info os.FileInfo, err error) error {
  46. if err != nil {
  47. return err
  48. }
  49. fmt.Println(" ", p, info.IsDir())
  50. return nil
  51. }

E-H

  1. package main
  2. import "fmt"
  3. //创建base结构体
  4. type base struct {
  5. age int
  6. num int
  7. }
  8. //(参数列表):b base (返回值类型)describe() string
  9. func (b base) describe() string {
  10. return fmt.Sprintf("base with num=%v", b.num)
  11. }
  12. //创建container结构体,包含base?
  13. type container struct {
  14. base
  15. str string
  16. }
  17. func main() {
  18. //co 是container的一个对象
  19. co := container{
  20. //必须对base进行显示初始化
  21. base: base{
  22. num: 1,
  23. },
  24. str: "some name",
  25. }
  26. fmt.Printf("co={num: %v, str: %v}\n", co.num, co.str)
  27. fmt.Println("also num:", co.base.num)
  28. //co(container)->base str->base.describe
  29. //两种访问方法均可
  30. //fmt.Println("describe:", co.base.describe()) --1
  31. fmt.Println("describe:", co.describe()) //--2
  32. //创建一个describer接口 访问describe方法
  33. type describer interface {
  34. describe() string
  35. }
  36. var d describer = co
  37. fmt.Println("describer:", d.describe())
  38. }
  39. // Circle ----------------------------
  40. //比如说,在2D绘图程序当中,我们可能会定义以下两个结构类型
  41. //圆圈
  42. /*
  43. type Circle struct {
  44. X, Y, Radius int
  45. }
  46. //Wheel 车轮
  47. type Wheel struct {
  48. X, Y, Radius, Spokes int
  49. }
  50. func main() {
  51. var w Wheel
  52. w.X = 8
  53. w.Y = 8
  54. w.Radius = 5
  55. w.Spokes = 20
  56. }
  57. */
  58. //--------------------------------------
  59. //但是当支持的形状变多了之后 我们需要重构相同的部分
  60. //--------------------------------------
  61. /*
  62. type Point struct {
  63. X,Y int
  64. }
  65. type Circle struct {
  66. Center Point
  67. Radius int
  68. }
  69. type Wheel struct {
  70. Circle Circle
  71. Spokes int
  72. }
  73. func main() {
  74. var w Wheel
  75. w.Circle.Center.X = 8
  76. w.Circle.Center.Y = 8
  77. w.Circle.Radius = 5
  78. w.Spokes = 20
  79. }
  80. */
  81. //程序结构简单了,但是访问wheel成员变得麻烦了
  82. //----------------------------
  83. //结构体嵌套和匿名成员的引入
  84. //匿名成员:Go允许我们定义不带名称的结构体成员,只需要指定类型即可;
  85. //这种结构体成员称作匿名成员。这个结构体成员的类型必须是一个命名类型
  86. //或者指向命名类型的指针
  87. /*
  88. type Point struct {
  89. X,Y int
  90. }
  91. type Circle struct {
  92. Point
  93. Radius int
  94. }
  95. type Wheel struct {
  96. Circle
  97. Spokes int
  98. }
  99. func main() {
  100. var w Wheel
  101. w.X = 8
  102. w.Y = 8
  103. w.Radius = 5
  104. w.Spokes = 20
  105. }
  106. */
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "strings"
  6. )
  7. func main() {
  8. os.Setenv("FOO", "1")
  9. fmt.Println("FOO:", os.Getenv("FOO"))
  10. fmt.Println("BAR:", os.Getenv("BAR"))
  11. fmt.Println()
  12. for _, e := range os.Environ() {
  13. pair := strings.SplitN(e, "=", 2)
  14. fmt.Println(pair[0])
  15. }
  16. }
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. now := time.Now()
  8. secs := now.Unix()
  9. nanos := now.UnixNano()
  10. fmt.Println(now)
  11. millis := nanos / 1000000
  12. fmt.Println(secs)
  13. fmt.Println(millis)
  14. fmt.Println(nanos)
  15. fmt.Println(time.Unix(secs, 0))
  16. fmt.Println(time.Unix(0, nanos))
  17. }
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. )
  6. //参数arg 返回int error两个参数
  7. func f1(arg int) (int, error) {
  8. //若arg==42
  9. if arg == 42 {
  10. //返回int=-1 error 错误信息 can't work with 42
  11. return -1, errors.New("can't work with 42")
  12. }
  13. //若不是则返回arg+3 , nil
  14. return arg + 3, nil
  15. }
  16. //定义argError结构体
  17. type argError struct {
  18. arg int
  19. prob string
  20. }
  21. func (e *argError) Error() string {
  22. return fmt.Sprintf("%d - %s", e.arg, e.prob)
  23. }
  24. func f2(arg int) (int, error) {
  25. if arg == 42 {
  26. return -1, &argError{arg, "can't work with it"}
  27. }
  28. return arg + 3, nil
  29. }
  30. func main() {
  31. //遍历{7,42}这个切片,空白化(索引值index)(key)值为_,value值为i。
  32. for _, i := range []int{7, 42} {
  33. //第一遍
  34. //i=7, r,e传入f1中的int error两个参数,当e 不为nil时
  35. //转到f1判断,因为i->arg=7 != 42 ->return arg+3,nil ->r=10,e=nil
  36. //不满足if条件 走else分支
  37. //第二遍
  38. //i=42,其他同上,向f1方法传入i=42的值->return -1,errors.New(can't work with 42)
  39. //满足if条件。打印f1 failed:can't work with 42------------------②
  40. if r, e := f1(i); e != nil {
  41. fmt.Println("f1 failed:", e)
  42. } else {
  43. fmt.Println("f1 worked:", r) //打印 f1 worked: 10 ------①
  44. }
  45. }
  46. //第一遍同上
  47. //第二遍 return -1, &argError{arg, "can't work with it"}
  48. for _, i := range []int{7, 42} {
  49. if r, e := f2(i); e != nil {
  50. fmt.Println("f2 failed:", e) //打印 f2 failed: 42 - can't work with it----④
  51. } else {
  52. fmt.Println("f2 worked:", r) //打印 f2 worked: 10 ------③
  53. }
  54. }
  55. //e接收f2返回的信息 &argError{arg, "can't work with it"}
  56. _, e := f2(42)
  57. //ar ok 分别接收e的arg 和 字符串;当ok也就是字符串不为空时
  58. if ae, ok := e.(*argError); ok {
  59. //打印两条语句
  60. fmt.Println(ae.arg)
  61. fmt.Println(ae.prob)
  62. }
  63. }
  1. package main
  2. import (
  3. "os"
  4. "os/exec"
  5. "syscall"
  6. )
  7. func main() {
  8. binary, lookErr := exec.LookPath("ls")
  9. if lookErr != nil {
  10. panic(lookErr)
  11. }
  12. args := []string{"ls", "-a", "-l", "-h"}
  13. env := os.Environ()
  14. //execErr := syscall.Exec(binary, args, env)
  15. if execErr != nil {
  16. panic(execErr)
  17. }
  18. }
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "strings"
  6. )
  7. func main() {
  8. // ! 不会被打印出来
  9. defer fmt.Println("!")
  10. os.Exit(3)
  11. }
  12. func twoSum(nums []int, target int) []int {
  13. //1.暴力解法
  14. // for i:=0;i<len(nums);i++{
  15. // for j := 0;j<len(nums);j++{
  16. // if nums[i]+nums[j] == target && i!= j{
  17. // return []int{i,j}
  18. // }
  19. // }
  20. // }
  21. // return nil
  22. //2.哈希表
  23. m := map[int]int{}
  24. for i := 0; i < len(nums); i++ {
  25. other := target - nums[i]
  26. if p, ok := m[other]; ok {
  27. return []int{p, i}
  28. }
  29. m[nums[i]] = i
  30. }
  31. return nil
  32. }
  33. func isPalindrome(s string) bool {
  34. q, p := 0, len(s)-1
  35. s = strings.ToUpper(s)
  36. for q <= p {
  37. //确保左右两边都是有效字符
  38. if !ischar(s[q]) {
  39. q++
  40. } else if !ischar(s[p]) {
  41. p--
  42. } else if s[q] != s[p] {
  43. return false
  44. }
  45. //是字符,正常左右两边走
  46. q++
  47. p--
  48. }
  49. return true
  50. }
  51. func ischar(ch byte) bool {
  52. return (ch <= 'Z' && ch >= 'A') || (ch >= '0' && ch <= '9')
  53. }
  1. package main
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "strings"
  6. )
  7. func main() {
  8. p := filepath.Join("dir1", "dir2", "filename")
  9. fmt.Println("p:", p)
  10. fmt.Println(filepath.Join("dir1//", "filename"))
  11. fmt.Println(filepath.Join("dir1/../dir1", "filename"))
  12. fmt.Println("Dir(p):", filepath.Dir(p))
  13. fmt.Println("Base(p):", filepath.Base(p))
  14. fmt.Println(filepath.IsAbs("dir/file"))
  15. fmt.Println(filepath.IsAbs("/dir/file"))
  16. filename := "config.json"
  17. ext := filepath.Ext(filename)
  18. fmt.Println(ext)
  19. fmt.Println(strings.TrimSuffix(filename, ext))
  20. rel, err := filepath.Rel("a/b", "a/b/t/file")
  21. if err != nil {
  22. panic(err)
  23. }
  24. fmt.Println(rel)
  25. rel, err = filepath.Rel("a/b", "a/c/t/file")
  26. if err != nil {
  27. panic(err)
  28. }
  29. fmt.Println(rel)
  30. }
  1. package main
  2. import "fmt"
  3. func main() {
  4. //1-3
  5. i := 1
  6. for i <= 3 {
  7. fmt.Println(i)
  8. i = i + 1
  9. }
  10. //7-9
  11. for j := 7; j <= 9; j++ {
  12. fmt.Println(j)
  13. }
  14. //loop 相当于 while(true){break}
  15. for {
  16. fmt.Println("loop")
  17. break
  18. }
  19. //打印奇数(0-5之间)
  20. for n := 0; n <= 5; n++ {
  21. if n%2 == 0 {
  22. continue
  23. }
  24. fmt.Println(n)
  25. }
  26. }
  1. package main
  2. import "fmt"
  3. func plus(a int, b int) int {
  4. return a + b
  5. }
  6. func plusPlus(a, b, c int) int {
  7. return a + b + c
  8. }
  9. func main() {
  10. res := plus(1, 2)
  11. fmt.Println("1+2 =", res)
  12. res = plusPlus(1, 2, 3)
  13. fmt.Println("1+2+3 =", res)
  14. }
  1. package main
  2. import "fmt"
  3. // MapKeys 泛型:类型参数
  4. // -----------------------------------------------------------------
  5. // type comparable interface{ comparable }
  6. // comparable是一个由所有可比较类型实现的接口
  7. // (布尔值、数字、字符串、指针、通道、可比类型数组、结构的字段都是可比较的类型)。
  8. // 可比接口只能作为类型参数约束使用,不是变量的类型。
  9. // -----------------------------------------------------------------
  10. // type any = interface{}
  11. // any是接口{}的别名,在所有方面都等价于接口{}。
  12. func MapKeys[K comparable, V any](m map[K]V) []K {
  13. //属实没看懂...
  14. r := make([]K, 0, len(m))
  15. for k := range m {
  16. r = append(r, k)
  17. }
  18. return r
  19. }
  20. type List[T any] struct {
  21. head, tail *element[T]
  22. }
  23. type element[T any] struct {
  24. next *element[T]
  25. val T
  26. }
  27. func (lst *List[T]) Push(v T) {
  28. if lst.tail == nil {
  29. lst.head = &element[T]{val: v}
  30. lst.tail = lst.head
  31. } else {
  32. lst.tail.next = &element[T]{val: v}
  33. lst.tail = lst.tail.next
  34. }
  35. }
  36. func (lst *List[T]) GetAll() []T {
  37. var elems []T
  38. for e := lst.head; e != nil; e = e.next {
  39. elems = append(elems, e.val)
  40. }
  41. return elems
  42. }
  43. func main() {
  44. //创建一个map key(int)-value(string) 并赋初值
  45. var m = map[int]string{1: "2", 2: "4", 4: "8"}
  46. //打印keys值 1 2 4
  47. fmt.Println("keys m:", MapKeys(m))
  48. _ = MapKeys[int, string](m)
  49. lst := List[int]{}
  50. lst.Push(10)
  51. lst.Push(13)
  52. lst.Push(23)
  53. fmt.Println("list:", lst.GetAll())
  54. }
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func f(from string) {
  7. for i := 0; i < 10; i++ {
  8. //解锁fmt.Println用法
  9. //func Println(a ...any) (n int, err error) {
  10. // return Fprintln(os.Stdout, a...)
  11. //}
  12. fmt.Println(from, ":", i)
  13. }
  14. }
  15. func main() {
  16. //并发执行direct 和 goroutine
  17. //异步进行
  18. f("direct")
  19. //go f(s) 在一个协程中调用这个函数。 这个新的 Go 协程将会 并发地 执行这个函数。
  20. go f("goroutine")
  21. //going的位置会不确定
  22. go func(msg string) {
  23. fmt.Println(msg)
  24. }("going")
  25. time.Sleep(time.Second)
  26. fmt.Println("done")
  27. }
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "net/http"
  6. )
  7. func main() {
  8. resp, err := http.Get("http://gobyexample.com")
  9. if err != nil {
  10. panic(err)
  11. }
  12. defer resp.Body.Close()
  13. fmt.Println("Response status:", resp.Status)
  14. scanner := bufio.NewScanner(resp.Body)
  15. for i := 0; scanner.Scan() && i < 5; i++ {
  16. fmt.Println(scanner.Text())
  17. }
  18. if err := scanner.Err(); err != nil {
  19. panic(err)
  20. }
  21. }
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. )
  6. func hello(w http.ResponseWriter, req *http.Request) {
  7. fmt.Fprintf(w, "hello\n")
  8. }
  9. func headers(w http.ResponseWriter, req *http.Request) {
  10. for name, headers := range req.Header {
  11. for _, h := range headers {
  12. fmt.Fprintf(w, "%v: %v\n", name, h)
  13. }
  14. }
  15. }
  16. func main() {
  17. http.HandleFunc("/hello", hello)
  18. http.HandleFunc("/headers", headers)
  19. http.ListenAndServe(":8090", nil)
  20. }

I-L

  1. package main
  2. import "fmt"
  3. func main() {
  4. //判断奇偶
  5. if 7%2 == 0 {
  6. fmt.Println("7 is even") //偶数
  7. } else {
  8. fmt.Println("7 is odd") //奇数
  9. }
  10. //能否整除
  11. if 8%4 == 0 {
  12. fmt.Println("8 is divisible by 4")
  13. }
  14. //判断数是一位数还是多位数(0-∞),其余输出负数
  15. //注: C/C++ Java 都有的三元运算符,在Go中并没有
  16. //圆括号可以省略不写(推荐不写) {}是必需的
  17. if num := 9; num < 0 {
  18. fmt.Println(num, "is negative")
  19. } else if num < 10 {
  20. fmt.Println(num, "has 1 digit")
  21. } else {
  22. fmt.Println(num, "has multiple digits")
  23. }
  24. }
  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. //接口对area perim 两种方法进行了再次抽象
  7. type geometry interface {
  8. area() float64
  9. perim() float64
  10. }
  11. type rect struct {
  12. width, height float64
  13. }
  14. type circle struct {
  15. radius float64
  16. }
  17. func (r rect) area() float64 {
  18. return r.width * r.height
  19. }
  20. func (r rect) perim() float64 {
  21. return 2*r.width + 2*r.height
  22. }
  23. func (c circle) area() float64 {
  24. return math.Pi * c.radius * c.radius
  25. }
  26. func (c circle) perim() float64 {
  27. return 2 * math.Pi * c.radius
  28. }
  29. //geometry:几何体
  30. func measure(g geometry) {
  31. //输出自身: {3 4}、 {5}
  32. fmt.Println(g)
  33. //输出面积/周长
  34. fmt.Println(g.area())
  35. fmt.Println(g.perim())
  36. }
  37. func main() {
  38. //创建r(rest)结构体 宽3高4
  39. r := rect{width: 3, height: 4}
  40. //创建⚪(circle) 半径5
  41. c := circle{radius: 5}
  42. measure(r)
  43. measure(c)
  44. }
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. )
  7. type response1 struct {
  8. Page int
  9. Fruits []string
  10. }
  11. type response2 struct {
  12. Page int `json:"page"`
  13. Fruits []string `json:"fruits"`
  14. }
  15. func main() {
  16. bolB, _ := json.Marshal(true)
  17. fmt.Println(string(bolB))
  18. intB, _ := json.Marshal(1)
  19. fmt.Println(string(intB))
  20. fltB, _ := json.Marshal(2.34)
  21. fmt.Println(string(fltB))
  22. strB, _ := json.Marshal("gopher")
  23. fmt.Println(string(strB))
  24. slcD := []string{"apple", "peach", "pear"}
  25. slcB, _ := json.Marshal(slcD)
  26. fmt.Println(string(slcB))
  27. mapD := map[string]int{"apple": 5, "lettuce": 7}
  28. mapB, _ := json.Marshal(mapD)
  29. fmt.Println(string(mapB))
  30. res1D := &response1{
  31. Page: 1,
  32. Fruits: []string{"apple", "peach", "pear"}}
  33. res1B, _ := json.Marshal(res1D)
  34. fmt.Println(string(res1B))
  35. res2D := &response2{
  36. Page: 1,
  37. Fruits: []string{"apple", "peach", "pear"}}
  38. res2B, _ := json.Marshal(res2D)
  39. fmt.Println(string(res2B))
  40. byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
  41. var dat map[string]interface{}
  42. if err := json.Unmarshal(byt, &dat); err != nil {
  43. panic(err)
  44. }
  45. fmt.Println(dat)
  46. num := dat["num"].(float64)
  47. fmt.Println(num)
  48. strs := dat["strs"].([]interface{})
  49. str1 := strs[0].(string)
  50. fmt.Println(str1)
  51. str := `{"page": 1, "fruits": ["apple", "peach"]}`
  52. res := response2{}
  53. json.Unmarshal([]byte(str), &res)
  54. fmt.Println(res)
  55. fmt.Println(res.Fruits[0])
  56. enc := json.NewEncoder(os.Stdout)
  57. d := map[string]int{"apple": 5, "lettuce": 7}
  58. enc.Encode(d)
  59. }
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "strings"
  7. )
  8. func main() {
  9. scanner := bufio.NewScanner(os.Stdin)
  10. for scanner.Scan() {
  11. ucl := strings.ToUpper(scanner.Text())
  12. fmt.Println(ucl)
  13. }
  14. if err := scanner.Err(); err != nil {
  15. fmt.Fprintln(os.Stderr, "error:", err)
  16. os.Exit(1)
  17. }
  18. }

M-P

  1. package main
  2. import "fmt"
  3. func main() {
  4. fmt.Println("hello world")
  5. }
  1. package main
  2. import "fmt"
  3. func main() {
  4. m := make(map[string]int)
  5. //建立map key-value类型 key:string value:int
  6. m["k1"] = 7
  7. m["k2"] = 13
  8. fmt.Println("map:", m)
  9. v1 := m["k1"]
  10. fmt.Println("v1: ", v1)
  11. fmt.Println("len:", len(m)) //2
  12. //删除key 为 k2的键
  13. delete(m, "k2")
  14. fmt.Println("map:", m)
  15. //面对不需要的值用 _ 空白标识符
  16. _, prs := m["k2"]
  17. fmt.Println("prs:", prs) //false
  18. n := map[string]int{"foo": 1, "bar": 2}
  19. fmt.Println("map:", n)
  20. }
  1. package main
  2. import "fmt"
  3. type rect1 struct {
  4. width, height int
  5. }
  6. //method1
  7. func (r *rect1) area() int {
  8. return r.width * r.height
  9. }
  10. //method2
  11. func (r rect1) perim() int {
  12. return 2*r.width + 2*r.height
  13. }
  14. func main() {
  15. //rect是矩形
  16. //创建结构体r(rect)并赋默认值
  17. r := rect{width: 10, height: 5}
  18. //使用m1计算面积
  19. fmt.Println("area: ", r.area())
  20. //使用m1计算周长
  21. fmt.Println("perim:", r.perim())
  22. //通过使用指针来避免拷贝(浪费空间)
  23. rp := &r
  24. fmt.Println("area: ", rp.area())
  25. fmt.Println("perim:", rp.perim())
  26. }
  1. package main
  2. import "fmt"
  3. func vals() (int, int) {
  4. return 3, 7
  5. }
  6. func main() {
  7. //支持多返回值
  8. a, b := vals()
  9. fmt.Println(a)
  10. fmt.Println(b)
  11. _, c := vals()
  12. fmt.Println(c)
  13. }
  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. )
  6. type Container struct {
  7. mu sync.Mutex
  8. counters map[string]int
  9. }
  10. func (c *Container) inc(name string) {
  11. c.mu.Lock()
  12. defer c.mu.Unlock()
  13. c.counters[name]++
  14. }
  15. func main() {
  16. c := Container{
  17. counters: map[string]int{"a": 0, "b": 0},
  18. }
  19. var wg sync.WaitGroup
  20. doIncrement := func(name string, n int) {
  21. for i := 0; i < n; i++ {
  22. c.inc(name)
  23. }
  24. wg.Done()
  25. }
  26. wg.Add(3)
  27. go doIncrement("a", 10000)
  28. go doIncrement("a", 10000)
  29. go doIncrement("b", 10000)
  30. wg.Wait()
  31. fmt.Println(c.counters)
  32. }
  1. package main
  2. import "fmt"
  3. func main() {
  4. messages := make(chan string)
  5. signals := make(chan bool)
  6. select {
  7. case msg := <-messages:
  8. fmt.Println("received message", msg)
  9. default:
  10. fmt.Println("no message received")
  11. }
  12. msg := "hi"
  13. select {
  14. case messages <- msg:
  15. fmt.Println("sent message", msg)
  16. default:
  17. fmt.Println("no message sent")
  18. }
  19. select {
  20. case msg := <-messages:
  21. fmt.Println("received message", msg)
  22. case sig := <-signals:
  23. fmt.Println("received signal", sig)
  24. default:
  25. fmt.Println("no activity")
  26. }
  27. }
  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. func main() {
  7. f, _ := strconv.ParseFloat("1.234", 64)
  8. fmt.Println(f)
  9. i, _ := strconv.ParseInt("123", 0, 64)
  10. fmt.Println(i)
  11. d, _ := strconv.ParseInt("0x1c8", 0, 64)
  12. fmt.Println(d)
  13. u, _ := strconv.ParseUint("789", 0, 64)
  14. fmt.Println(u)
  15. k, _ := strconv.Atoi("135")
  16. fmt.Println(k)
  17. _, e := strconv.Atoi("wat")
  18. fmt.Println(e)
  19. }
  1. package main
  2. import "os"
  3. func main() {
  4. panic("a problem")
  5. _, err := os.Create("/tmp/file")
  6. if err != nil {
  7. panic(err)
  8. }
  9. }
  1. package main
  2. import "fmt"
  3. //值传递
  4. func zeroval(ival int) {
  5. ival = 0
  6. }
  7. //“引用”传递 ->本质还是值传递,只不过值变成了指针所指的逻辑地址
  8. func zeroptr(iptr *int) {
  9. *iptr = 0
  10. }
  11. func main() {
  12. i := 1
  13. fmt.Println("initial:", i)
  14. zeroval(i)
  15. fmt.Println("zeroval:", i)
  16. zeroptr(&i)
  17. fmt.Println("zeroptr:", i)
  18. //打印i所在的逻辑地址(每个人机器打出来的值都会有所不同,由OS分配)
  19. //fmt.Println(&i) 0xc000016098
  20. fmt.Println("pointer:", &i)
  21. }

R-S

  1. package main
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "time"
  6. )
  7. func main() {
  8. //生成随机数0-100
  9. fmt.Print(rand.Intn(100), ",")
  10. fmt.Print(rand.Intn(100))
  11. fmt.Println()
  12. //生成随机float64位浮点数(0.0-1.0)
  13. fmt.Println(rand.Float64())
  14. //5.0-10.0
  15. fmt.Print((rand.Float64()*5)+5, ",")
  16. fmt.Print((rand.Float64() * 5) + 5)
  17. fmt.Println()
  18. s1 := rand.NewSource(time.Now().UnixNano())
  19. r1 := rand.New(s1)
  20. fmt.Print(r1.Intn(100), ",")
  21. fmt.Print(r1.Intn(100))
  22. fmt.Println()
  23. //使用相同种子生成的随机数生成器,会生成相同的随机数序列
  24. s2 := rand.NewSource(42)
  25. r2 := rand.New(s2)
  26. //此处①
  27. fmt.Print(r2.Intn(100), ",")
  28. fmt.Print(r2.Intn(100))
  29. fmt.Println()
  30. s3 := rand.NewSource(42)
  31. r3 := rand.New(s3)
  32. //此处②同①生成相同的两个随机数
  33. fmt.Print(r3.Intn(100), ",")
  34. fmt.Print(r3.Intn(100))
  35. }
  1. package main
  2. import "fmt"
  3. func main() {
  4. //创建切片nums len = 3
  5. nums := []int{2, 3, 4}
  6. sum := 0
  7. //对nums中的数据求和,存放在num中
  8. for _, num := range nums {
  9. sum += num
  10. }
  11. fmt.Println("sum:", sum)
  12. //取出num ==3时,对应的索引值
  13. for i, num := range nums {
  14. if num == 3 {
  15. fmt.Println("index:", i)
  16. }
  17. }
  18. //创建key-value的map
  19. kvs := map[string]string{"a": "apple", "b": "banana", "p": "peach"}
  20. //随机取值 map无序
  21. for k, v := range kvs {
  22. fmt.Printf("%s -> %s\n", k, v)
  23. }
  24. for k := range kvs {
  25. fmt.Println("key:", k)
  26. }
  27. for i, c := range "go" {
  28. //字符串 输出索引值 0 1 和其对应的ascii码值
  29. fmt.Println(i, c)
  30. //Output:
  31. //0 103
  32. //1 111
  33. }
  34. }
  1. package main
  2. import "fmt"
  3. func main() {
  4. queue := make(chan string, 2)
  5. queue <- "one"
  6. queue <- "two"
  7. close(queue)
  8. for elem := range queue {
  9. fmt.Println(elem)
  10. }
  11. }
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. requests := make(chan int, 5)
  8. for i := 1; i <= 5; i++ {
  9. requests <- i
  10. }
  11. close(requests)
  12. limiter := time.Tick(200 * time.Millisecond)
  13. for req := range requests {
  14. <-limiter
  15. fmt.Println("request", req, time.Now())
  16. }
  17. burstyLimiter := make(chan time.Time, 3)
  18. for i := 0; i < 3; i++ {
  19. burstyLimiter <- time.Now()
  20. }
  21. go func() {
  22. for t := range time.Tick(200 * time.Millisecond) {
  23. burstyLimiter <- t
  24. }
  25. }()
  26. burstyRequests := make(chan int, 5)
  27. for i := 1; i <= 5; i++ {
  28. burstyRequests <- i
  29. }
  30. close(burstyRequests)
  31. for req := range burstyRequests {
  32. <-burstyLimiter
  33. fmt.Println("request", req, time.Now())
  34. }
  35. }
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "os"
  7. )
  8. func check(e error) {
  9. if e != nil {
  10. panic(e)
  11. }
  12. }
  13. func main() {
  14. dat, err := os.ReadFile("/tmp/dat")
  15. check(err)
  16. fmt.Print(string(dat))
  17. f, err := os.Open("/tmp/dat")
  18. check(err)
  19. b1 := make([]byte, 5)
  20. n1, err := f.Read(b1)
  21. check(err)
  22. fmt.Printf("%d bytes: %s\n", n1, string(b1[:n1]))
  23. o2, err := f.Seek(6, 0)
  24. check(err)
  25. b2 := make([]byte, 2)
  26. n2, err := f.Read(b2)
  27. check(err)
  28. fmt.Printf("%d bytes @ %d: ", n2, o2)
  29. fmt.Printf("%v\n", string(b2[:n2]))
  30. o3, err := f.Seek(6, 0)
  31. check(err)
  32. b3 := make([]byte, 2)
  33. n3, err := io.ReadAtLeast(f, b3, 2)
  34. check(err)
  35. fmt.Printf("%d bytes @ %d: %s\n", n3, o3, string(b3))
  36. _, err = f.Seek(0, 0)
  37. check(err)
  38. r4 := bufio.NewReader(f)
  39. b4, err := r4.Peek(5)
  40. check(err)
  41. fmt.Printf("5 bytes: %s\n", string(b4))
  42. f.Close()
  43. }
  1. package main
  2. import "fmt"
  3. func mayPanic() {
  4. panic("a problem")
  5. }
  6. func main() {
  7. defer func() {
  8. if r := recover(); r != nil {
  9. fmt.Println("Recovered. Error:\n", r)
  10. }
  11. }()
  12. mayPanic()
  13. fmt.Println("After mayPanic()")
  14. }
  1. package main
  2. import "fmt"
  3. func fact(n int) int {
  4. if n == 0 {
  5. return 1
  6. }
  7. return n * fact(n-1)
  8. }
  9. func main() {
  10. //计算7的阶乘
  11. fmt.Println(fact(7))
  12. //1 2 6 24 120 720 5040...
  13. var fib func(n int) int
  14. //计算斐波那契数列
  15. fib = func(n int) int {
  16. if n < 2 {
  17. return n
  18. }
  19. return fib(n-1) + fib(n-2)
  20. }
  21. //1 1 2 3 5 8 13...
  22. fmt.Println(fib(7))
  23. }
  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "regexp"
  6. )
  7. func main() {
  8. match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
  9. fmt.Println(match)
  10. r, _ := regexp.Compile("p([a-z]+)ch")
  11. fmt.Println(r.MatchString("peach"))
  12. fmt.Println(r.FindString("peach punch"))
  13. fmt.Println("idx:", r.FindStringIndex("peach punch"))
  14. fmt.Println(r.FindStringSubmatch("peach punch"))
  15. fmt.Println(r.FindStringSubmatchIndex("peach punch"))
  16. fmt.Println(r.FindAllString("peach punch pinch", -1))
  17. fmt.Println("all:", r.FindAllStringSubmatchIndex(
  18. "peach punch pinch", -1))
  19. fmt.Println(r.FindAllString("peach punch pinch", 2))
  20. fmt.Println(r.Match([]byte("peach")))
  21. r = regexp.MustCompile("p([a-z]+)ch")
  22. fmt.Println("regexp:", r)
  23. fmt.Println(r.ReplaceAllString("a peach", "<fruit>"))
  24. in := []byte("a peach")
  25. out := r.ReplaceAllFunc(in, bytes.ToUpper)
  26. fmt.Println(string(out))
  27. }
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. c1 := make(chan string)
  8. c2 := make(chan string)
  9. go func() {
  10. time.Sleep(1 * time.Second)
  11. c1 <- "one"
  12. }()
  13. go func() {
  14. time.Sleep(2 * time.Second)
  15. c2 <- "two"
  16. }()
  17. for i := 0; i < 2; i++ {
  18. select {
  19. case msg1 := <-c1:
  20. fmt.Println("received", msg1)
  21. case msg2 := <-c2:
  22. fmt.Println("received", msg2)
  23. }
  24. }
  25. }
  1. package main
  2. import (
  3. "crypto/sha256"
  4. "fmt"
  5. )
  6. func main() {
  7. s := "sha256 this string"
  8. h := sha256.New()
  9. h.Write([]byte(s))
  10. bs := h.Sum(nil)
  11. fmt.Println(s)
  12. fmt.Printf("%x\n", bs)
  13. }
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "os/signal"
  6. "syscall"
  7. )
  8. func main() {
  9. sigs := make(chan os.Signal, 1)
  10. signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
  11. done := make(chan bool, 1)
  12. go func() {
  13. sig := <-sigs
  14. fmt.Println()
  15. fmt.Println(sig)
  16. done <- true
  17. }()
  18. fmt.Println("awaiting signal")
  19. <-done
  20. fmt.Println("exiting")
  21. }
  1. package main
  2. import "fmt"
  3. func main() {
  4. //创建切片,默认值为空字符串 ""
  5. s := make([]string, 3)
  6. fmt.Println("emp:", s)
  7. //对s切片赋值a b c
  8. s[0] = "a"
  9. s[1] = "b"
  10. s[2] = "c"
  11. fmt.Println("set:", s)
  12. fmt.Println("get:", s[2])
  13. //获取长度
  14. fmt.Println("len:", len(s))
  15. //向s中追加 "d"
  16. s = append(s, "d")
  17. //slice 扩容可查看src/runtime/slice.go 下的 growslice 函数
  18. s = append(s, "e", "f")
  19. fmt.Println("apd:", s)
  20. //创建与c同样大小的c slice
  21. c := make([]string, len(s))
  22. //切片复制
  23. copy(c, s)
  24. fmt.Println("cpy:", c)
  25. //左取右不取
  26. l := s[2:5]
  27. fmt.Println("sl1:", l)
  28. l = s[:5]
  29. fmt.Println("sl2:", l)
  30. l = s[2:]
  31. fmt.Println("sl3:", l)
  32. t := []string{"g", "h", "i"}
  33. fmt.Println("dcl:", t)
  34. //二维切片
  35. twoD := make([][]int, 3)
  36. for i := 0; i < 3; i++ {
  37. innerLen := i + 1
  38. twoD[i] = make([]int, innerLen)
  39. for j := 0; j < innerLen; j++ {
  40. twoD[i][j] = i + j
  41. }
  42. }
  43. fmt.Println("2d: ", twoD)
  44. //OutPut: [[0] [1 2] [2 3 4]]
  45. }
  1. package main
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. func main() {
  7. strs := []string{"c", "a", "b"}
  8. sort.Strings(strs)
  9. fmt.Println("Strings:", strs)
  10. ints := []int{7, 2, 4}
  11. sort.Ints(ints)
  12. fmt.Println("Ints: ", ints)
  13. s := sort.IntsAreSorted(ints)
  14. fmt.Println("Sorted: ", s)
  15. }
  1. package main
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. type byLength []string
  7. func (s byLength) Len() int {
  8. return len(s)
  9. }
  10. func (s byLength) Swap(i, j int) {
  11. s[i], s[j] = s[j], s[i]
  12. }
  13. func (s byLength) Less(i, j int) bool {
  14. return len(s[i]) < len(s[j])
  15. }
  16. func main() {
  17. fruits := []string{"peach", "banana", "kiwi"}
  18. sort.Sort(byLength(fruits))
  19. fmt.Println(fruits)
  20. }
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "os/exec"
  6. )
  7. func main() {
  8. dateCmd := exec.Command("date")
  9. dateOut, err := dateCmd.Output()
  10. if err != nil {
  11. panic(err)
  12. }
  13. fmt.Println("> date")
  14. fmt.Println(string(dateOut))
  15. grepCmd := exec.Command("grep", "hello")
  16. grepIn, _ := grepCmd.StdinPipe()
  17. grepOut, _ := grepCmd.StdoutPipe()
  18. grepCmd.Start()
  19. grepIn.Write([]byte("hello grep\ngoodbye grep"))
  20. grepIn.Close()
  21. grepBytes, _ := io.ReadAll(grepOut)
  22. grepCmd.Wait()
  23. fmt.Println("> grep hello")
  24. fmt.Println(string(grepBytes))
  25. lsCmd := exec.Command("bash", "-c", "ls -a -l -h")
  26. lsOut, err := lsCmd.Output()
  27. if err != nil {
  28. panic(err)
  29. }
  30. fmt.Println("> ls -a -l -h")
  31. fmt.Println(string(lsOut))
  32. }
  1. package main
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "sync/atomic"
  6. "time"
  7. )
  8. type readOp struct {
  9. key int
  10. resp chan int
  11. }
  12. type writeOp struct {
  13. key int
  14. val int
  15. resp chan bool
  16. }
  17. func main() {
  18. var readOps uint64
  19. var writeOps uint64
  20. reads := make(chan readOp)
  21. writes := make(chan writeOp)
  22. go func() {
  23. var state = make(map[int]int)
  24. for {
  25. select {
  26. case read := <-reads:
  27. read.resp <- state[read.key]
  28. case write := <-writes:
  29. state[write.key] = write.val
  30. write.resp <- true
  31. }
  32. }
  33. }()
  34. for r := 0; r < 100; r++ {
  35. go func() {
  36. for {
  37. read := readOp{
  38. key: rand.Intn(5),
  39. resp: make(chan int)}
  40. reads <- read
  41. <-read.resp
  42. atomic.AddUint64(&readOps, 1)
  43. time.Sleep(time.Millisecond)
  44. }
  45. }()
  46. }
  47. for w := 0; w < 10; w++ {
  48. go func() {
  49. for {
  50. write := writeOp{
  51. key: rand.Intn(5),
  52. val: rand.Intn(100),
  53. resp: make(chan bool)}
  54. writes <- write
  55. <-write.resp
  56. atomic.AddUint64(&writeOps, 1)
  57. time.Sleep(time.Millisecond)
  58. }
  59. }()
  60. }
  61. time.Sleep(time.Second)
  62. readOpsFinal := atomic.LoadUint64(&readOps)
  63. fmt.Println("readOps:", readOpsFinal)
  64. writeOpsFinal := atomic.LoadUint64(&writeOps)
  65. fmt.Println("writeOps:", writeOpsFinal)
  66. }
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. )
  6. type point struct {
  7. x, y int
  8. }
  9. func main() {
  10. p := point{1, 2}
  11. fmt.Printf("struct1: %v\n", p)
  12. fmt.Printf("struct2: %+v\n", p)
  13. fmt.Printf("struct3: %#v\n", p)
  14. fmt.Printf("type: %T\n", p)
  15. fmt.Printf("bool: %t\n", true)
  16. fmt.Printf("int: %d\n", 123)
  17. fmt.Printf("bin: %b\n", 14)
  18. fmt.Printf("char: %c\n", 33)
  19. fmt.Printf("hex: %x\n", 456)
  20. fmt.Printf("float1: %f\n", 78.9)
  21. fmt.Printf("float2: %e\n", 123400000.0)
  22. fmt.Printf("float3: %E\n", 123400000.0)
  23. fmt.Printf("str1: %s\n", "\"string\"")
  24. fmt.Printf("str2: %q\n", "\"string\"")
  25. fmt.Printf("str3: %x\n", "hex this")
  26. fmt.Printf("pointer: %p\n", &p)
  27. fmt.Printf("width1: |%6d|%6d|\n", 12, 345)
  28. fmt.Printf("width2: |%6.2f|%6.2f|\n", 1.2, 3.45)
  29. fmt.Printf("width3: |%-6.2f|%-6.2f|\n", 1.2, 3.45)
  30. fmt.Printf("width4: |%6s|%6s|\n", "foo", "b")
  31. fmt.Printf("width5: |%-6s|%-6s|\n", "foo", "b")
  32. s := fmt.Sprintf("sprintf: a %s", "string")
  33. fmt.Println(s)
  34. fmt.Fprintf(os.Stderr, "io: an %s\n", "error")
  35. }
  1. package main
  2. import (
  3. "fmt"
  4. s "strings"
  5. )
  6. var p = fmt.Println
  7. func main() {
  8. p("Contains: ", s.Contains("test", "es"))
  9. p("Count: ", s.Count("test", "t"))
  10. p("HasPrefix: ", s.HasPrefix("test", "te"))
  11. p("HasSuffix: ", s.HasSuffix("test", "st"))
  12. p("Index: ", s.Index("test", "e"))
  13. p("Join: ", s.Join([]string{"a", "b"}, "-"))
  14. p("Repeat: ", s.Repeat("a", 5))
  15. p("Replace: ", s.Replace("foo", "o", "0", -1))
  16. p("Replace: ", s.Replace("foo", "o", "0", 1))
  17. p("Split: ", s.Split("a-b-c-d-e", "-"))
  18. p("ToLower: ", s.ToLower("TEST"))
  19. p("ToUpper: ", s.ToUpper("test"))
  20. p()
  21. p("Len: ", len("hello"))
  22. p("Char:", "hello"[1])
  23. }
  1. package main
  2. import (
  3. "fmt"
  4. "unicode/utf8"
  5. )
  6. func main() {
  7. //电脑用光标移动,会数出六个字符 6*3 = 18
  8. const s = "สวัสดี"
  9. //打印的长长度是计算的byte值
  10. fmt.Println("Len:", len(s))
  11. //打印[]byte值 共18个
  12. for i := 0; i < len(s); i++ {
  13. fmt.Printf("%x ", s[i])
  14. }
  15. //e0 b8 aa e0 b8 a7 e0 b8 b1 e0 b8 aa e0 b8 94 e0 b8 b5
  16. fmt.Println()
  17. fmt.Println("Rune count:", utf8.RuneCountInString(s))
  18. //分别打印UTF-8 code point值和其偏移量
  19. for idx, runeValue := range s {
  20. fmt.Printf("%#U starts at %d\n", runeValue, idx)
  21. }
  22. fmt.Println("\nUsing DecodeRuneInString")
  23. for i, w := 0, 0; i < len(s); i += w {
  24. runeValue, width := utf8.DecodeRuneInString(s[i:])
  25. fmt.Printf("%#U starts at %d\n", runeValue, i)
  26. w = width
  27. examineRune(runeValue)
  28. }
  29. }
  30. func examineRune(r rune) {
  31. if r == 't' {
  32. fmt.Println("found tee")
  33. } else if r == 'ส' {
  34. fmt.Println("found so sua")
  35. }
  36. }
  1. package main
  2. import "fmt"
  3. //创建结构体 person 包含name age两个字段
  4. type person struct {
  5. name string
  6. age int
  7. }
  8. func newPerson(name string) *person {
  9. p := person{name: name}
  10. p.age = 42
  11. return &p
  12. }
  13. func main() {
  14. fmt.Println(person{"Bob", 20})
  15. fmt.Println(person{name: "Alice", age: 30})
  16. fmt.Println(person{name: "Fred"})
  17. fmt.Println(&person{name: "Ann", age: 40})
  18. fmt.Println(newPerson("Jon"))
  19. s := person{name: "Sean", age: 50}
  20. fmt.Println(s.name)
  21. //对结构体指针使用 . 指针会被自动解引用。
  22. sp := &s
  23. fmt.Println(sp.age)
  24. //修改结构体对应的字段值
  25. sp.age = 51
  26. fmt.Println(sp.age)
  27. }
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. //switch不需要break,Go中会自动添加
  8. i := 2
  9. fmt.Print("write ", i, " as ")
  10. switch i {
  11. case 1:
  12. fmt.Println("one")
  13. case 2:
  14. fmt.Println("two")
  15. case 3:
  16. fmt.Println("three")
  17. }
  18. switch time.Now().Weekday() {
  19. case time.Saturday, time.Sunday:
  20. fmt.Println("It's the weekend")
  21. default:
  22. fmt.Println("It's a weekday")
  23. }
  24. t := time.Now()
  25. switch {
  26. case t.Hour() < 12:
  27. fmt.Println("It's before noon")
  28. default:
  29. fmt.Println("It's after noon")
  30. }
  31. //类型开关type switch比较类型,而非value.以此判断参数的类型值
  32. whatAmI := func(i interface{}) {
  33. switch t := i.(type) {
  34. case bool:
  35. fmt.Println("I'm a bool")
  36. case int:
  37. fmt.Println("I'm an int")
  38. default:
  39. fmt.Printf("Don't know type %T\n", t)
  40. }
  41. }
  42. whatAmI(true)
  43. whatAmI(1)
  44. whatAmI("hey")
  45. }

T-X

  1. package main
  2. import (
  3. "os"
  4. "text/template"
  5. )
  6. func main() {
  7. t1 := template.New("t1")
  8. t1, err := t1.Parse("Value is {{.}}\n")
  9. if err != nil {
  10. panic(err)
  11. }
  12. t1 = template.Must(t1.Parse("Value: {{.}}\n"))
  13. t1.Execute(os.Stdout, "some text")
  14. t1.Execute(os.Stdout, 5)
  15. t1.Execute(os.Stdout, []string{
  16. "Go",
  17. "Rust",
  18. "C++",
  19. "C#",
  20. })
  21. Create := func(name, t string) *template.Template {
  22. return template.Must(template.New(name).Parse(t))
  23. }
  24. t2 := Create("t2", "Name: {{.Name}}\n")
  25. t2.Execute(os.Stdout, struct {
  26. Name string
  27. }{"Jane Doe"})
  28. t2.Execute(os.Stdout, map[string]string{
  29. "Name": "Mickey Mouse",
  30. })
  31. t3 := Create("t3",
  32. "{{if . -}} yes {{else -}} no {{end}}\n")
  33. t3.Execute(os.Stdout, "not empty")
  34. t3.Execute(os.Stdout, "")
  35. t4 := Create("t4",
  36. "Range: {{range .}}{{.}} {{end}}\n")
  37. t4.Execute(os.Stdout,
  38. []string{
  39. "Go",
  40. "Rust",
  41. "C++",
  42. "C#",
  43. })
  44. }
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. )
  7. func check3(e error) {
  8. if e != nil {
  9. panic(e)
  10. }
  11. }
  12. func main() {
  13. f, err := os.CreateTemp("", "sample")
  14. check3(err)
  15. fmt.Println("Temp file name:", f.Name())
  16. defer os.Remove(f.Name())
  17. _, err = f.Write([]byte{1, 2, 3, 4})
  18. check3(err)
  19. dname, err := os.MkdirTemp("", "sampledir")
  20. fmt.Println("Temp dir name:", dname)
  21. defer os.RemoveAll(dname)
  22. fname := filepath.Join(dname, "file1")
  23. err = os.WriteFile(fname, []byte{1, 2}, 0666)
  24. check3(err)
  25. }
  1. package main
  2. import (
  3. "fmt"
  4. "testing"
  5. )
  6. func IntMin(a, b int) int {
  7. if a < b {
  8. return a
  9. }
  10. return b
  11. }
  12. func TestIntMinBasic(t *testing.T) {
  13. ans := IntMin(2, -2)
  14. if ans != -2 {
  15. t.Errorf("IntMin(2, -2) = %d; want -2", ans)
  16. }
  17. }
  18. func TestIntMinTableDriven(t *testing.T) {
  19. var tests = []struct {
  20. a, b int
  21. want int
  22. }{
  23. {0, 1, 0},
  24. {1, 0, 0},
  25. {2, -2, -2},
  26. {0, -1, -1},
  27. {-1, 0, -1},
  28. }
  29. for _, tt := range tests {
  30. testname := fmt.Sprintf("%d,%d", tt.a, tt.b)
  31. t.Run(testname, func(t *testing.T) {
  32. ans := IntMin(tt.a, tt.b)
  33. if ans != tt.want {
  34. t.Errorf("got %d, want %d", ans, tt.want)
  35. }
  36. })
  37. }
  38. }
  39. func BenchmarkIntMin(b *testing.B) {
  40. for i := 0; i < b.N; i++ {
  41. IntMin(1, 2)
  42. }
  43. }
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. ticker := time.NewTicker(500 * time.Millisecond)
  8. done := make(chan bool)
  9. go func() {
  10. for {
  11. select {
  12. case <-done:
  13. return
  14. case t := <-ticker.C:
  15. fmt.Println("Tick at", t)
  16. }
  17. }
  18. }()
  19. time.Sleep(1600 * time.Millisecond)
  20. ticker.Stop()
  21. done <- true
  22. fmt.Println("Ticker stopped")
  23. }
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. p := fmt.Println
  8. now := time.Now()
  9. p(now)
  10. then := time.Date(
  11. 2009, 11, 17, 20, 34, 58, 651387237, time.UTC)
  12. p(then)
  13. p(then.Year())
  14. p(then.Month())
  15. p(then.Day())
  16. p(then.Hour())
  17. p(then.Minute())
  18. p(then.Second())
  19. p(then.Nanosecond())
  20. p(then.Location())
  21. p(then.Weekday())
  22. p(then.Before(now))
  23. p(then.After(now))
  24. p(then.Equal(now))
  25. diff := now.Sub(then)
  26. p(diff)
  27. p(diff.Hours())
  28. p(diff.Minutes())
  29. p(diff.Seconds())
  30. p(diff.Nanoseconds())
  31. p(then.Add(diff))
  32. p(then.Add(-diff))
  33. }
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. p := fmt.Println
  8. t := time.Now()
  9. p(t.Format(time.RFC3339))
  10. t1, e := time.Parse(
  11. time.RFC3339,
  12. "2012-11-01T22:08:41+00:00")
  13. p(t1)
  14. p(t.Format("3:04PM"))
  15. p(t.Format("Mon Jan _2 15:04:05 2006"))
  16. p(t.Format("2006-01-02T15:04:05.999999-07:00"))
  17. form := "3 04 PM"
  18. t2, e := time.Parse(form, "8 41 PM")
  19. p(t2)
  20. fmt.Printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
  21. t.Year(), t.Month(), t.Day(),
  22. t.Hour(), t.Minute(), t.Second())
  23. ansic := "Mon Jan _2 15:04:05 2006"
  24. _, e = time.Parse(ansic, "8:41PM")
  25. p(e)
  26. }
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. c1 := make(chan string, 1)
  8. go func() {
  9. time.Sleep(2 * time.Second)
  10. c1 <- "result 1"
  11. }()
  12. select {
  13. case res := <-c1:
  14. fmt.Println(res)
  15. case <-time.After(1 * time.Second):
  16. fmt.Println("timeout 1")
  17. }
  18. c2 := make(chan string, 1)
  19. go func() {
  20. time.Sleep(2 * time.Second)
  21. c2 <- "result 2"
  22. }()
  23. select {
  24. case res := <-c2:
  25. fmt.Println(res)
  26. case <-time.After(3 * time.Second):
  27. fmt.Println("timeout 2")
  28. }
  29. }
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. timer1 := time.NewTimer(2 * time.Second)
  8. <-timer1.C
  9. fmt.Println("Timer 1 fired")
  10. timer2 := time.NewTimer(time.Second)
  11. go func() {
  12. <-timer2.C
  13. fmt.Println("Timer 2 fired")
  14. }()
  15. stop2 := timer2.Stop()
  16. if stop2 {
  17. fmt.Println("Timer 2 stopped")
  18. }
  19. time.Sleep(2 * time.Second)
  20. }
  1. package main
  2. import (
  3. "fmt"
  4. "net"
  5. "net/url"
  6. )
  7. func main() {
  8. s := "postgres://user:pass@host.com:5432/path?k=v#f"
  9. u, err := url.Parse(s)
  10. if err != nil {
  11. panic(err)
  12. }
  13. fmt.Println(u.Scheme)
  14. fmt.Println(u.User)
  15. fmt.Println(u.User.Username())
  16. p, _ := u.User.Password()
  17. fmt.Println(p)
  18. fmt.Println(u.Host)
  19. host, port, _ := net.SplitHostPort(u.Host)
  20. fmt.Println(host)
  21. fmt.Println(port)
  22. fmt.Println(u.Path)
  23. fmt.Println(u.Fragment)
  24. fmt.Println(u.RawQuery)
  25. m, _ := url.ParseQuery(u.RawQuery)
  26. fmt.Println(m)
  27. fmt.Println(m["k"][0])
  28. }
  1. package main
  2. import "fmt"
  3. func main() {
  4. fmt.Println("go" + "lang")
  5. fmt.Println("1+1 =", 1+1)
  6. fmt.Println("7.0/3.0 =", 7.0/3.0)
  7. //运用逻辑运算符
  8. fmt.Println(true && false)
  9. fmt.Println(true || false)
  10. fmt.Println(!true)
  11. }
  1. package main
  2. import "fmt"
  3. func main() {
  4. var a = "initial"
  5. fmt.Println(a)
  6. var b, c int = 1, 2
  7. fmt.Println(b, c)
  8. var d = true
  9. fmt.Println(d)
  10. var e int
  11. fmt.Println(e)
  12. //短变量声明 :=
  13. f := "short"
  14. fmt.Println(f)
  15. }
  1. package main
  2. import "fmt"
  3. //通过使用 ... 使函数接收任意数量的int作为参数
  4. func sum(nums ...int) {
  5. fmt.Print(nums, " ")
  6. total := 0
  7. for _, num := range nums {
  8. total += num
  9. }
  10. fmt.Println(total)
  11. }
  12. func main() {
  13. sum(1, 2)
  14. sum(1, 2, 3)
  15. nums := []int{1, 2, 3, 4}
  16. sum(nums...)
  17. }
  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. "time"
  6. )
  7. func worker2(id int) {
  8. fmt.Printf("Worker %d starting\n", id)
  9. time.Sleep(time.Second)
  10. fmt.Printf("Worker %d done\n", id)
  11. }
  12. func main() {
  13. var wg sync.WaitGroup
  14. for i := 1; i <= 5; i++ {
  15. wg.Add(1)
  16. i := i
  17. go func() {
  18. defer wg.Done()
  19. worker2(i)
  20. }()
  21. }
  22. wg.Wait()
  23. }
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func worker(id int, jobs <-chan int, results chan<- int) {
  7. for j := range jobs {
  8. fmt.Println("worker", id, "started job", j)
  9. time.Sleep(time.Second)
  10. fmt.Println("worker", id, "finished job", j)
  11. results <- j * 2
  12. }
  13. }
  14. func main() {
  15. const numJobs = 5
  16. jobs := make(chan int, numJobs)
  17. results := make(chan int, numJobs)
  18. for w := 1; w <= 3; w++ {
  19. go worker(w, jobs, results)
  20. }
  21. for j := 1; j <= numJobs; j++ {
  22. jobs <- j
  23. }
  24. close(jobs)
  25. for a := 1; a <= numJobs; a++ {
  26. <-results
  27. }
  28. }
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. )
  7. func check1(e error) {
  8. if e != nil {
  9. panic(e)
  10. }
  11. }
  12. func main() {
  13. d1 := []byte("hello\ngo\n")
  14. err := os.WriteFile("/tmp/dat1", d1, 0644)
  15. check1(err)
  16. f, err := os.Create("/tmp/dat2")
  17. check1(err)
  18. defer f.Close()
  19. d2 := []byte{115, 111, 109, 101, 10}
  20. n2, err := f.Write(d2)
  21. check1(err)
  22. fmt.Printf("wrote %d bytes\n", n2)
  23. n3, err := f.WriteString("writes\n")
  24. check1(err)
  25. fmt.Printf("wrote %d bytes\n", n3)
  26. f.Sync()
  27. w := bufio.NewWriter(f)
  28. n4, err := w.WriteString("buffered\n")
  29. check1(err)
  30. fmt.Printf("wrote %d bytes\n", n4)
  31. w.Flush()
  32. }
  1. package main
  2. import (
  3. "encoding/xml"
  4. "fmt"
  5. )
  6. type Plant struct {
  7. XMLName xml.Name `xml:"plant"`
  8. Id int `xml:"id,attr"`
  9. Name string `xml:"name"`
  10. Origin []string `xml:"origin"`
  11. }
  12. func (p Plant) String() string {
  13. return fmt.Sprintf("Plant id=%v, name=%v, origin=%v",
  14. p.Id, p.Name, p.Origin)
  15. }
  16. func main() {
  17. coffee := &Plant{Id: 27, Name: "Coffee"}
  18. coffee.Origin = []string{"Ethiopia", "Brazil"}
  19. out, _ := xml.MarshalIndent(coffee, " ", " ")
  20. fmt.Println(string(out))
  21. fmt.Println(xml.Header + string(out))
  22. var p Plant
  23. if err := xml.Unmarshal(out, &p); err != nil {
  24. panic(err)
  25. }
  26. fmt.Println(p)
  27. tomato := &Plant{Id: 81, Name: "Tomato"}
  28. tomato.Origin = []string{"Mexico", "California"}
  29. type Nesting struct {
  30. XMLName xml.Name `xml:"nesting"`
  31. Plants []*Plant `xml:"parent>child>plant"`
  32. }
  33. nesting := &Nesting{}
  34. nesting.Plants = []*Plant{coffee, tomato}
  35. out, _ = xml.MarshalIndent(nesting, " ", " ")
  36. fmt.Println(string(out))
  37. }