Home >Backend Development >Golang >How Can I Reuse Arguments in Go's fmt.Printf?

How Can I Reuse Arguments in Go's fmt.Printf?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-16 03:55:10167browse

How Can I Reuse Arguments in Go's fmt.Printf?

Reusing Arguments in fmt.Printf

In Python's print function, you can reuse an argument value by specifying it once and referencing it multiple times using the {} syntax. However, Go's fmt.Printf function does not have a similar mechanism.

Solution

To reuse an argument value in fmt.Printf, you can use the [n] notation to reference arguments explicitly. For example, to print the same value twice using the argument i:

fmt.Printf("%[1]d %[1]d\n", i)

In this expression, %[1] refers to the first argument, which is i. By using this approach, you can avoid declaring the argument multiple times and keep your code concise.

Here is an example you can try out:

package main

import "fmt"

func main() {
    i := 10
    fmt.Printf("%[1]d %[1]d\n", i)
}

Output:

10 10

The above is the detailed content of How Can I Reuse Arguments in Go's fmt.Printf?. 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