1.先读README.md文件

安装 color 库
$ go get /fatih/color

1.jpg

2.实例测试

标准颜色代码

// Print with default helper functions
color.Cyan("Prints text in cyan.")

// A newline will be appended automatically
color.Blue("Prints %s in blue.", "text")

// These are using the default foreground colors
color.Red("We have red")
color.Magenta("And many others ..")

2.jpg

本地电脑测试

/main.go

package main

import (
	"/fatih/color"
)

func main() {
	// Print with default helper functions
	color.Cyan("Prints text in cyan.")

	// A newline will be appended automatically
	color.Blue("Prints %s in blue.", "text")

	// These are using the default foreground colors
	color.Red("We have red")
	color.Magenta("And many others ..")
}

3.jpg

3.代码解读

a.从一条代码开始解读

// 用青色打印内容
color.Cyan("Prints text in cyan.")

// 按住ctrl键,点击 Cyan 函数代码

4.jpg

b.查看color库中的Cyan 函数代码

// color库中的Cyan 函数代
// 在这里我们传入了字符串,接着将字符串带入函数体,将字符串传给colorPrint函数
// 按住ctrl键,点击 FgCyan 函数代码

func Cyan(format string, a ...interface{}) { colorPrint(format, FgCyan, a...) }

5.jpg

c.查看参数FgCyan

// 查看代码可知:
1.FgCyan是类型为 Attribute 的常量,值为36

6.jpg

d.查看 Attribute 是什么

// 查看代码可知:
1.Attribute 类型可以被定义为 int 的别名

7.jpg

f.查看函数 colorPrint

// 由上面代码可知:
1.Cyan 函数将字符串传给 colorPrint 函数
2.colorPrint 函数的第二参数带上常量FgCyan(值为36),第一参数是前面传入的字符串

8.jpg

colorPrint函数
1.获取p对应的颜色结构体Color
2.如果输出的字符没有换行符,就加上换行符
3.如果不是格式化,就执行 c.Print(format) ,否则执行 c.Printf(format, a...)

9.jpg

g.颜色打印函数

10.jpg