本章将探讨一种基本的着色机制,为红色或纯文本着色。有关完整的应用程序,请查看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.这会输出:

说明
这里的演示比较简单,大家可以搜索相关颜色和第三方库学习用法。
最后编辑: kuteng  文档更新时间: 2021-01-03 15:03   作者:kuteng