Home > Backend Development > Golang > How to Reference the Same Parameter Multiple Times in fmt.Sprintf Format Strings?

How to Reference the Same Parameter Multiple Times in fmt.Sprintf Format Strings?

Susan Sarandon
Release: 2024-11-07 16:38:02
Original
847 people have browsed it

How to Reference the Same Parameter Multiple Times in fmt.Sprintf Format Strings?

Referencing the Same Parameter Multiple Times in fmt.Sprintf Format Strings

In the given code snippet, you have a function that generates SQL commands to create tables using fmt.Sprintf. While the original approach is verbose, you desire a way to reference the v parameter only once for better string formatting.

According to the documentation for fmt.Sprintf:

In Printf, Sprintf, and Fprintf, the default behavior is for each formatting verb to format successive arguments passed in the call. However, the notation [n] immediately before the verb indicates that the nth one-indexed argument is to be formatted instead.

This means you can pass the v variable once and use the [n] notation to specify the argument index to be formatted. For example, your updated function can be:

func getTableCreationCommands(v string) string {
    return fmt.Sprintf(`
        CREATE TABLE share_%[1]v PARTITION OF share FOR VALUES IN (%[1]v);
        CREATE TABLE nearby_%[1]v PARTITION OF nearby FOR VALUES IN (%[1]v);
    `, v)
}
Copy after login

Here, %[1]v tells the formatter to use the first argument, which is v, twice.

To use this function:

import "fmt"

func main() {
    s := "X"
    fmt.Println(getTableCreationCommands(s))
}
Copy after login

Output:

CREATE TABLE share_X PARTITION OF share FOR VALUES IN (X);
CREATE TABLE nearby_X PARTITION OF nearby FOR VALUES IN (X);
Copy after login

This approach provides a cleaner and more concise way to format your SQL commands with multiple references to the same parameter.

The above is the detailed content of How to Reference the Same Parameter Multiple Times in fmt.Sprintf Format Strings?. 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