Home > Backend Development > Golang > How Can I Reuse the Same Parameter Multiple Times in a Go fmt.Sprintf Format String?

How Can I Reuse the Same Parameter Multiple Times in a Go fmt.Sprintf Format String?

DDD
Release: 2024-11-07 05:55:03
Original
905 people have browsed it

How Can I Reuse the Same Parameter Multiple Times in a Go fmt.Sprintf Format String?

How to Refer to the Same Parameter Multiple Times in a fmt.Sprintf Format String

In Go, the fmt package provides a convenient way to format strings using the Sprintf function. However, it can be cumbersome to specify the same parameter multiple times within the format string.

Consider the following example:

func getTableCreationCommands(v string) string {
    return `
        CREATE TABLE share_` + v + ` PARTITION OF share FOR VALUES IN (` + v + `);
        CREATE TABLE nearby_` + v + ` PARTITION OF nearby FOR VALUES IN (` + v + `);
    `
}
Copy after login

Here, we have to repeat the parameter 'v' four times to create the SQL commands. Instead of this verbose approach, we can use explicit argument indexes to refer to the same parameter multiple times within the format string.

import "fmt"

func getTableCreationCommands(s 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);
    `, s)
}

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

In this modified function, we enclose the argument index [1] within square brackets before the formatting verb (%v), indicating that we want to use the first argument passed to Sprintf, which is the string "X" in this case. The Playground link for this snippet is https://play.golang.org/p/fKV3iviuwll.

Using explicit argument indexes allows us to pass the parameter only once and reference it as needed within the format string, resulting in a more concise and readable implementation.

The above is the detailed content of How Can I Reuse the Same Parameter Multiple Times in a Go fmt.Sprintf Format String?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template