Search code examples
govariadic-functions

Rewriting a fprint function in golang


I've found a package for printing colours in golang. However, it has no simple way of printing no colour. And as my code was becoming messier due being filled with print statements I wanted to rewrite it. However, I have no clue how to create fstrings in a function.

How it looks in my code:

color.HEX("#B0DFE5").Print("[" + time.Now().Format("15:04:05") +"] ")
color.HEX("#FFFFFF").Printf("Changed %s to %s\n", name, new_name)   

What I've created for normal prints:

func cprintInfo(message string) {
    color.HEX("#B0DFE5").Print("[!] ")
    color.HEX("#FFFFFF").Printf(message + "\n")   
}

What I'm looking to create:

cfprintInfo("Hello %s", world)
// Hello world

Solution

  • Printf() expects a format string and (optional) arguments:

    func (c RGBColor) Printf(format string, a ...interface{})
    

    So mimic that:

    func cfprintInfo(format string, args ...interface{}) {
        color.HEX("#B0DFE5").Print("[!] ")
        color.HEX("#FFFFFF").Printf(format, args...)
    }