助力软件开发企业降本增效 PHP / java源码系统,只需一次付费,代码终身使用! 广告
## ANSI文本着色 本章将探讨一种基本的着色机制,为红色或纯文本着色。有关完整的应用程序,请查看[https//github.com/agtorre/gocolorize](https//github.com/agtorre/gocolorize) ,它支持更多颜色和文本类型,并且还实现了fmt.Formatter接口以方便打印。 ### 实践 1. 创建color.go: ``` package ansicolor import "fmt" //文本的颜色 type Color int const ( // 默认颜色 ColorNone = iota Red Green Yellow Blue Magenta Cyan White Black Color = -1 ) // ColorText 存储了文本及所属的颜色 type ColorText struct { TextColor Color Text string } func (r *ColorText) String() string { if r.TextColor == ColorNone { return r.Text } value := 30 if r.TextColor != Black { value += int(r.TextColor) } return fmt.Sprintf("\033[0;%dm%s\033[0m", value, r.Text) } ``` 2. 创建main.go: ``` package main import ( "fmt" "github.com/agtorre/go-cookbook/chapter2/ansicolor" ) func main() { r := ansicolor.ColorText{ TextColor: ansicolor.Red, Text: "I'm red!", } fmt.Println(r.String()) r.TextColor = ansicolor.Green r.Text = "Now I'm green!" fmt.Println(r.String()) r.TextColor = ansicolor.ColorNone r.Text = "Back to normal..." fmt.Println(r.String()) } ``` 3. 这会输出: ![](https://box.kancloud.cn/665227f69fe3b44f48f6fe41de5aa750_155x77.jpg) ### 说明 这里的演示比较简单,大家可以搜索相关颜色和第三方库学习用法。 * * * * 学识浅薄,错误在所难免。欢迎在群中就本书提出修改意见,以飨后来者,长风拜谢。 Golang中国(211938256) beego实战(258969317) Go实践(386056972)