Why not use% v to print int and string

I know that for printing int we can use %d and string , we can use %s but we can use %v to print them. So what if I always use %v to print them? What will be the problem if I do this?

+6
source share
1 answer

Nothing bad will happen, but the verb %d tells fmt to print as a number (using base 10), and the verb %v means using the default format, which can be overridden.

See this example:

 type MyInt int func (mi MyInt) String() string { return fmt.Sprint("*", int(mi), "*") } func main() { var mi MyInt = 2 fmt.Printf("%d %v", mi, mi) } 

Exit (try on the Go Playground ):

 2 *2* 

When using the verb %v the fmt package checks if the value implements the fmt.Stringer interface (which is a single String() string ), and if so, this method will be called to convert the value to string (which can be formatted further if flags are specified )

A complete list of formatting rules is in the doc fmt package, quoting the corresponding part:

Unless they are printed using the verbs% T and% p, special formatting considerations apply for operands that implement certain interfaces. In order of application:

  • If the operand is a reflection. The value, the operand, is replaced by the specific value that it holds, and printing continues from the next rule.

  • If the operand implements the Formatter interface, it will be called. Formatter provides precise formatting control.

  • If the verb% v is used with the flag # (% # v), and the operand implements the GoStringer interface, which will be called.

If the format (implicitly% v for Println, etc.) is valid for the string (% s% q% v% x% X), the following two rules apply:

  1. If the operand implements the error interface, the Error method will be called to convert the object to a string, which will then be formatted in accordance with the requirements of the verb (if any).

  2. If the operand implements the string of the String () method, this method will be called to convert the object to a string, which will then be formatted in accordance with the requirements of the verb (if any).

+9
source

Source: https://habr.com/ru/post/1013175/


All Articles