I am trying to write a functional that wraps FPrintf however I keep getting weird characters out.
Here is an reproducer
https://play.golang.org/p/yZgNnpovEa
The idea is to be able to have a conditional Printf which I can test the output (Thus use of FPrintf so I can test the output towards the input). Is there any way to get around this?
I have seen How to ignore extra fields for fmt.Sprintf but all answers there assume the user is expecting only %s while in my case I want to be as flexible as Printf and the only other one is downvoted.
Is this just not possible and can anybody give a reasonable explanation why?
The problem is you actually send an empty slice to fmt.Fprintf
. Additional check of params' length should fix the problem.
func (p ConditionalPrinter) printF(s string, params ...interface{}) {
if p.print {
if len(params) == 0 {
fmt.Fprintf(p.writer, s)
} else {
fmt.Fprintf(p.writer, s, params)
}
}
}
Or this:
func (p ConditionalPrinter) printF(s string, params ...interface{}) {
switch {
case !p.print:
return
case len(params) == 0:
fmt.Fprintf(p.writer, s)
default:
fmt.Fprintf(p.writer, s, params)
}
}
See Playground link