重写一个在Go语言中的fprint函数。

huangapple go评论83阅读模式
英文:

Rewriting a fprint function in golang

问题

我找到了一个在Go语言中打印颜色的包。然而,它没有简单的方法来打印颜色。由于我的代码中充斥着打印语句,导致代码变得混乱,我想重写它。然而,我不知道如何在函数中创建fstrings。

在我的代码中是这样的:

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

我为普通打印创建了以下内容:

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

我想要创建的是:

cfprintInfo("Hello %s", world)
// Hello world
英文:

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

答案1

得分: 4

Printf() 函数需要一个格式字符串和(可选的)参数:

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

所以模仿这个函数:

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

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...)
}

huangapple
  • 本文由 发表于 2022年1月6日 04:55:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/70599464.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定