Home >Backend Development >Golang >How Can I Repeat a Variable in Go's fmt.Sprintf Using Argument Indexes?

How Can I Repeat a Variable in Go's fmt.Sprintf Using Argument Indexes?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-30 10:59:18859browse

How Can I Repeat a Variable in Go's fmt.Sprintf Using Argument Indexes?

Replicating Variables in Sprintf Utilizing Explicit Argument Indexes

In conventional fmt.Sprintf() usage, variables are sequentially substituted into the formatted string. However, it is feasible to replicate a single variable throughout the string.

Solution

Utilizing explicit argument indexes, the format string can be modified to reference the same argument multiple times:

val := "foo"
s := fmt.Sprintf("%[1]v in %[1]v is %[1]v", val)

The %[n] notation before a formatting verb specifies the index of the argument to be used. In this case, %[1] indicates that the first argument (val) should be used for all instances of the placeholder.

Output

Executing the modified Sprintf:

fmt.Println(s)

Produces:

foo in foo is foo

Effectively, every variable placehold in the string is replaced with the value of val, resulting in the desired replication.

Simplified Form

For the specific scenario where the first argument should be used consistently, the %[1] index can be omitted:

fmt.Sprintf("%v in %[1]v is %[1]v", "foo")

This abbreviated syntax simplifies the formatting string while still achieving the same replication functionality.

The above is the detailed content of How Can I Repeat a Variable in Go's fmt.Sprintf Using Argument Indexes?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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