Use the fmt.Sprintf function to format a string into a specified format

WBOY
Release: 2023-07-25 14:05:45
Original
1415 people have browsed it

Use the fmt.Sprintf function to format a string into a specified format

In the Go language, the fmt.Sprintf function is a very practical function that can format a string into a specified format. . It has a wide range of uses and can be used to build complex strings, including printing logs, generating error messages, etc.

Let's look at a simple example below. Suppose we have a structure of student information, including name, age and score. Now we need to format this information into a string so it can be printed.

First, we define a structure type to represent student information:

type Student struct {
    Name   string
    Age    int
    Score  float64
}
Copy after login

Next, we create a student object and assign a value:

student := Student{
    Name:   "小明",
    Age:    18,
    Score:  89.5,
}
Copy after login

Then, we use fmt The .Sprintf function formats student information into a string:

studentStr := fmt.Sprintf("姓名:%s,年龄:%d,分数:%.2f", student.Name, student.Age, student.Score)
Copy after login

In the above code, we use the placeholders %s, %d and %.2f, which represent strings, integers and floats respectively. Formatting of points.

Finally, we can print out the formatted student information:

fmt.Println(studentStr)
Copy after login

Run the above code, the output result is as follows:

姓名:小明,年龄:18,分数:89.50
Copy after login

In addition, fmt.Sprintf Functions can also be used to generate error messages. For example, when an error occurs while processing a file, we can use this function to format the relevant information into an error string and then return it to the caller.

In general, the fmt.Sprintf function is very practical in the Go language and can be used to format strings to achieve the output we want. Whether printing logs or generating error messages, it can help us simplify the code and improve readability.

I hope this article will help you understand the use of fmt.Sprintf function in Go language.

The above is the detailed content of Use the fmt.Sprintf function to format a string into a specified format. 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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!