There is an issue in fmt.printf()


(Mangal Arora) #1

var s = ‘a’
fmt.Printf("%T type of s\n",s,“mangalarora”)
fmt.Println(s)

Output:
int32 type of s
%!(EXTRA string=mangalarora)97

it should give an error instead of printing that it is an extra string output.


(Norbert Melzer) #2

Who said it should error?

It behaves as documented:

https://golang.org/pkg/fmt/

Format errors:

If an invalid argument is given for a verb, such as providing a string to %d, the generated string will contain a description of the problem, as in these examples:

Wrong type or unknown verb: %!verb(type=value)
	Printf("%d", hi):          %!d(string=hi)
Too many arguments: %!(EXTRA type=value)
	Printf("hi", "guys"):      hi%!(EXTRA string=guys)
Too few arguments: %!verb(MISSING)
	Printf("hi%d"):            hi%!d(MISSING)
Non-int for width or precision: %!(BADWIDTH) or %!(BADPREC)
	Printf("%*s", 4.5, "hi"):  %!(BADWIDTH)hi
	Printf("%.*s", 4.5, "hi"): %!(BADPREC)hi
Invalid or invalid use of argument index: %!(BADINDEX)
	Printf("%*[2]d", 7):       %!d(BADINDEX)
	Printf("%.[2]d", 7):       %!d(BADINDEX)

(Mangal Arora) #3

Thank You for letting me know that. I didn’t read documentation just started trying new things with Go.
and I think this should show error instead of showing extra string.


(Norbert Melzer) #4

Compile time error or runtime panic?

I’d appreciate an error at compile time, it would make things easier at times, but on the other hand side, the compiler would need to special case fmt.Printf and friends, and functions which wrap them with args... as eg. a logger would still need to deal with those at runtime.

A runtime panic though would be nasty… Especially for dynamically generated formatting strings/args it might make my program crash without me having an opportunity to do something about that, or I had to use a defered panic handler everywhere when I use something that prints… Not funny either…


(Johan Dahl) #5

Then using Visual Studio Code and the golang plugin it at least gives a warning. I guess this comes from go vet. But It doesn’t complain about the extra arguments.