[TOC] ## 打印中文字符 > rune相当于go的char ``` s := "我哈哈啊!" for _, v := range []rune(s) { fmt.Printf("%c \n",v) //每次打印一个字符 } ``` ## 递归+迭代实现无限级分类 > [参考网址] ``` type Cate struct { Id int `json:"id"` Name string `json:"name"` Pid int `json:"pid"` } type cateTree struct { Id int `json:"id"` Name string `json:"name"` Pid int `json:"pid"` Son []cateTree } func main() { allCate := []Cate{ {1, "a", 0}, {2, "b", 0}, {3, "c", 0}, {4, "aa", 1}, {5, "bb", 2}, {6, "cc", 3}, {7, "aaa", 4}, {8, "bbb", 5}, {9, "哈哈哈", 6}, {10, "ccc", 7}, } arr := superCategoryTree(allCate, 0) b, _ := json.Marshal(arr) fmt.Println("json:", string(b)) //必须使用string(b) 进行转义 } //@allCate 结构体数组 //@pid int 顶级id func superCategoryTree(allCate []Cate, pid int) []cateTree { var arr []cateTree for _, v := range allCate { if pid == v.Pid { ctree := cateTree{} ctree.Id = v.Id ctree.Pid = v.Pid ctree.Name = v.Name sonCate := superCategoryTree(allCate, v.Id) ctree.Son = sonCate arr = append(arr, ctree) } } return arr } ``` ## go 并发调用 python 或 shell > [参考代码](https://github.com/r00tjimmy/codeBox/blob/master/golang_basic/goroutine_exec.go) ``` var quit= make(chan int) func runComm() { cmd := exec.Command("date", "+%s.%N") out, err := cmd.CombinedOutput() if err != nil { fmt.Println(err) } fmt.Println(string(out)) time.Sleep(3*time.Second) quit <- 0 } func main() { runtime.GOMAXPROCS(2) go runComm() go runComm() for i := 0; i < 2; i++ { <- quit } } ``` ## 守护其他进程的代码 ``` func main() { lf, err := os.OpenFile("angel.txt", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0600) if err != nil { os.Exit(1) } defer lf.Close() // 日志 l := log.New(lf, "", os.O_APPEND) for { cmd := exec.Command("/usr/local/bin/node", "/*****.js") err := cmd.Start() if err != nil { l.Printf("%s 启动命令失败", time.Now().Format("2006-01-02 15:04:05"), err) time.Sleep(time.Second * 5) continue } l.Printf("%s 进程启动", time.Now().Format("2006-01-02 15:04:05"), err) err = cmd.Wait() l.Printf("%s 进程退出", time.Now().Format("2006-01-02 15:04:05"), err) time.Sleep(time.Second * 1) } } ``` ## 执行系统命令 如`cmd ls` ``` func main() { command := "ls" params := []string{"-l"} //执行cmd命令: ls -l execCommand(command, params) } func execCommand(commandName string, params []string) bool { cmd := exec.Command(commandName, params...) //显示运行的命令 fmt.Println(cmd.Args) stdout, err := cmd.StdoutPipe() if err != nil { fmt.Println(err) return false } cmd.Start() reader := bufio.NewReader(stdout) //实时循环读取输出流中的一行内容 for { line, err2 := reader.ReadString('\n') if err2 != nil || io.EOF == err2 { break } fmt.Println(line) } cmd.Wait() return true } ```