How to Handle Unexpected Fields in fmt.Sprintf?

Patricia Arquette
Release: 2024-10-31 19:05:02
Original
472 people have browsed it

How to Handle Unexpected Fields in fmt.Sprintf?

Handling Unexpected Fields in fmt.Sprintf

In Go programming, the fmt.Sprintf function is utilized to format strings. However, an issue arises when the input string contains unexpected fields, leading to a panic.

Problem

Let's consider the following code snippet:

<code class="go">package main

import "fmt"

func main() {
    tmp_str := "hello %s"
    str := fmt.Sprintf(tmp_str, "world")
    fmt.Println(str)
}</code>
Copy after login

In this example, tmp_str is a template string expecting a single argument. However, if the program receives a complete string like "Hello Friends" (instead of a template), fmt.Sprintf will panic due to the presence of an extra argument. The error message would be:

Hello Friends%!(EXTRA string=world)
Copy after login

Solution

One approach to handle this issue is to enforce the use of a valid %s verb in the template string. Users can provide a placeholder verb, such as %.0s or %.s, to indicate that the argument will be truncated to zero length if no matching field exists. Here's an example:

<code class="go">tmp_str := "Hello Friends%.s"</code>
Copy after login

Using %.s will truncate any extra fields, resulting in the desired output:

Hello Friends
Copy after login

The above is the detailed content of How to Handle Unexpected Fields in fmt.Sprintf?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!