1. 将字符串”hello,java教程”转化为”hello,go教程”
    1. package main
    2. import (
    3. "bytes"
    4. "fmt"
    5. "strings"
    6. )
    7. func main() {
    8. str1 := "hello,java教程"
    9. source := "java"
    10. target := "go"
    11. index := strings.Index(str1, source)
    12. sourceLen := len(source)
    13. start := str1[:index]
    14. end := str1[index+sourceLen:]
    15. var stringBuilder bytes.Buffer
    16. stringBuilder.WriteString(start)
    17. stringBuilder.WriteString(target)
    18. stringBuilder.WriteString(end)
    19. fmt.Println(stringBuilder.String())
    20. }
    1. 九九乘法表
    1. package main
    2. import "fmt"
    3. func main() {
    4. for y := 1; y <= 9; y++ {
    5. for x := 1; x <= y; x++ {
    6. fmt.Printf("%d*%d=%d ", x, y, x*y)
    7. }
    8. fmt.Println()
    9. }
    10. }
    1. 匿名函数用作回调函数
    1. package main
    2. import "fmt"
    3. func main() {
    4. visit([]int{1, 2, 3, 4}, func(v int) {
    5. fmt.Println(v)
    6. })
    7. }
    8. func visit(list []int, f func(int)) {
    9. for _, v := range list {
    10. f(v)
    11. }
    12. }
    1. 返回多个匿名函数
    1. package main
    2. import "fmt"
    3. func main() {
    4. f1, f2 := FGen(1, 2)
    5. fmt.Println(f1())
    6. fmt.Println(f2(3))
    7. }
    8. func FGen(x, y int) (func() int, func(int) int) {
    9. sum := func() int {
    10. return x + y
    11. }
    12. avg := func(z int) int {
    13. return (x + y) * z
    14. }
    15. return sum, avg
    16. }
    1. 闭包例子
    1. package main
    2. import "fmt"
    3. func main() {
    4. generator1 := playerGen1("yasuo")
    5. name1, hp1 := generator1()
    6. name2, hp2 := generator1()
    7. fmt.Println(name1, hp1)
    8. fmt.Println(name2, hp2)
    9. generator2 := playerGen2()
    10. name3, hp3 := generator2("yasuo")
    11. fmt.Println(name3, hp3)
    12. name4, hp4 := generator2("yone")
    13. fmt.Println(name4, hp4)
    14. }
    15. func playerGen1(name string) func() (string, int) {
    16. hp := 150
    17. return func() (string, int) {
    18. hp++
    19. return name, hp
    20. }
    21. }
    22. func playerGen2() func(string) (string, int) {
    23. hp := 150
    24. return func(name string) (string, int) {
    25. hp++
    26. return name, hp
    27. }
    28. }
    1. 读文件
    1. package main
    2. import (
    3. "fmt"
    4. "io"
    5. "os"
    6. )
    7. func main() {
    8. file, err := os.Open("./x.go")
    9. if err != nil {
    10. fmt.Println("open file err :", err)
    11. return
    12. }
    13. defer file.Close()
    14. var buf [128]byte
    15. var content []byte
    16. for {
    17. n, err := file.Read(buf[:])
    18. if err == io.EOF {
    19. break
    20. }
    21. if err != nil {
    22. fmt.Println("read file err :", err)
    23. return
    24. }
    25. content = append(content, buf[:n]...)
    26. }
    27. fmt.Println(string(content))
    28. }