Home > Backend Development > Golang > Can %v Print Both Integers and Strings in Go's `fmt.Printf`?

Can %v Print Both Integers and Strings in Go's `fmt.Printf`?

Susan Sarandon
Release: 2024-11-14 09:32:02
Original
1021 people have browsed it

Can %v Print Both Integers and Strings in Go's `fmt.Printf`?

Using %v to Print Different Data Types

It is common to encounter situations where we need to print both integers (%d) and strings (%s) using printf. One might wonder if it's possible to use %v for both types. While it is acceptable, using %v indiscriminately can lead to unexpected results.

Default Formatting of %v

fmt.Printf("%v") is a generic placeholder that prints the value using the "default" format, which can be overridden by specifying format flags. For integers, %v defaults to base 10 (%d) formatting. However, %v falls back to the fmt.Stringer interface for non-primitive types.

Consider the following 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)
}
Copy after login

Output:

2 *2*
Copy after login

In this case, %v respects the implementation of the String() method in MyInt and prints "2", overriding the default integer formatting.

Considerations

Using %v for both integers and strings is technically not wrong. However, it can result in formatting that may not be desirable in all situations. It's recommended to use the explicit format specifier (%d for integers and %s for strings) to ensure consistent and predictable formatting.

The above is the detailed content of Can %v Print Both Integers and Strings in Go's `fmt.Printf`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template