zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Golang:color在终端上输出带颜色的文字

输出Golang 颜色 文字 终端 Color
2023-09-27 14:24:15 时间

在这里插入图片描述
Color lets you use colorized outputs in terms of ANSI Escape Codes in Go (Golang). It has support for Windows too! The API can be used in several ways, pick one that suits you.

译文:Color 允许您根据Go(Golang)中的ANSI转义码使用着色输出。它也支持Windows!API可以多种方式使用,选择适合您的方式。

文档

安装

go get github.com/fatih/color

示例

// main.go

package main

import (
    "github.com/fatih/color"
)

func main() {
    // 直接使用,输出蓝色文字
    color.Blue("hello: %s", "Tom")

    // 实例化后使用
    colorPrint := color.New()
    colorPrint.Add(color.FgRed)   // 红色文字
    colorPrint.Add(color.Italic)  // 倾斜
    colorPrint.Add(color.BgGreen) // 绿色背景

    colorPrint.Println("Hello World")
}

注意:直接运行没有效果,需要在终端使用命令行运行才能看到效果

$ go run main.go

输出结果
在这里插入图片描述

参考
「Go工具箱」一个让终端内容彩色化的工具:Color