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

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

Rewriting a fprint function in golang

问题

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

在我的代码中是这样的:

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

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

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

我想要创建的是:

  1. cfprintInfo("Hello %s", world)
  2. // 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:

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

What I've created for normal prints:

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

What I'm looking to create:

  1. cfprintInfo("Hello %s", world)
  2. // Hello world

答案1

得分: 4

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

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

所以模仿这个函数:

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

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

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

So mimic that:

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

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:

确定