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