Home >Backend Development >Golang >Golang formatting placeholder usage tips
Golang formatting placeholder usage skills
In the process of using Golang for string formatting, it is very important to master the use of placeholders. . This article will introduce some commonly used formatting placeholders and sample code to help readers handle string formatting tasks more flexibly.
The formatting placeholder in Golang mainly consists of %
followed by specific letters, indicating the output of different types of data. The following are some commonly used formatting placeholders and their corresponding data types:
%v
: Default formatting, formatted output according to the type of value. %d
: Format an integer into a decimal number. %s
: Format and output the string. %f
: Format floating point number into decimal number. %t
: Format Boolean value. In addition to the above commonly used formatting placeholders, there are some other placeholders that are more flexible in usage, such as:
% v
: When outputting the structure, field names will be included. %-15s
: left-justified, output a string of 15 characters, and fill in the remaining parts with spaces. %#x
: Outputs the hexadecimal representation with a leading 0x
prefix. Let’s look at some specific code examples to show the usage skills of these placeholders:
%v
:name := "Alice" age := 30 fmt.Printf("Name: %v, Age: %v ", name, age)
%d
:num := 123 fmt.Printf("Number: %d ", num)
%s
:message := "Hello, World" fmt.Printf("Message: %s ", message)
%f
:pi := 3.14159 fmt.Printf("Pi: %.2f ", pi)
%t
: isGoCool := true fmt.Printf("Is Golang cool? %t ", isGoCool)
% v
:type Person struct { Name string Age int } person := Person{Name: "Bob", Age: 25} fmt.Printf("Person: %+v ", person)
Through the above example code, readers can better understand and master Golang Tips on using formatting placeholders, making it easier to handle string formatting tasks in actual development. Hope this article is helpful to readers!
The above is the detailed content of Golang formatting placeholder usage tips. For more information, please follow other related articles on the PHP Chinese website!