Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Print/Output text in color in console

Posted on March 29, 2023January 8, 2023 by admin

Note: If you are interested in learning Golang, then for that we have a golang comprehensive tutorial series. Do check it out –Golang Comprehensive Tutorial Series. Now let’s see the current tutorial. Below is the table of contents.

Table of Contents

  • Overview
  • Code

Overview

ANSI escape codes can be used to output colored text in console. Please note that

  • In MAC/Linux system terminal supports ANSI escape codes
  • Windows Command Prompt doesn’t support it. On windows you can install Cygwin. ANSI escape codes work on that.

Also to mention in the below code we have used colorReset after printing. If we don’t use that then the color effect remains and it is not cleared. Remove the colorReset from below code and it will show text “next” in cyan color
Below is code in golang to do the same.

Code

package main
import (
"fmt"
)
func main() {
colorReset := "\033[0m"
colorRed := "\033[31m"
colorGreen := "\033[32m"
colorYellow := "\033[33m"
colorBlue := "\033[34m"
colorPurple := "\033[35m"
colorCyan := "\033[36m"
colorWhite := "\033[37m"
fmt.Println(string(colorRed), "test")
fmt.Println(string(colorGreen), "test")
fmt.Println(string(colorYellow), "test")
fmt.Println(string(colorBlue), "test")
fmt.Println(string(colorPurple), "test")
fmt.Println(string(colorWhite), "test")
fmt.Println(string(colorCyan), "test", string(colorReset))
fmt.Println("next")
}

Output:

On my mac machine

  • ansi
  • color
  • console
  • go
  • output
  • print
  • terminal
  • text
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP