I know to print int
we can use %d
, and string
we can use %s
but we can still use %v
to print them. So what if I always use %v
to print them? What issue will happen if I do this?
The verbs behave analogously to those of Printf. For example, %x will scan an integer as a hexadecimal number, and %v will scan the default representation format for the value. The Printf verbs %p and %T and the flags # and + are not implemented.
Use comma “,” to separate strings and variables while printing int and string in the same line in Python or convert the int to string.
Use %t to format a boolean as true or false .
Nothing bad will happen, but the %d
verb instructs the fmt
package to print is as a number (using base 10), and the %v
verb means to use 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) }
Output (try it on the Go Playground):
2 *2*
When using the %v
verb, the fmt
package checks if the value implements the fmt.Stringer
interface (which is a single String() string
method), and if so, that method will be called to convert the value to string
(which may be formatted further if flags are specified).
The complete list of formatting rules is in the package doc of fmt
, quoting the relevant part:
Except when 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 reflect.Value, the operand is replaced by the concrete value that it holds, and printing continues with the next rule.
If an operand implements the Formatter interface, it will be invoked. Formatter provides fine control of formatting.
If the %v verb is used with the # flag (%#v) and the operand implements the GoStringer interface, that will be invoked.
If the format (which is implicitly %v for Println etc.) is valid for a string (%s %q %v %x %X), the following two rules apply:
If an operand implements the error interface, the Error method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).
If an operand implements method String() string, that method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With