Home > Backend Development > Golang > How can I reference parameters multiple times in fmt.Sprintf format strings?

How can I reference parameters multiple times in fmt.Sprintf format strings?

DDD
Release: 2024-11-09 05:34:02
Original
392 people have browsed it

How can I reference parameters multiple times in fmt.Sprintf format strings?

Referencing Parameters Multiple Times in fmt.Sprintf Format Strings

In your code, you have a function that creates table creation commands using fmt.Sprintf. You want to avoid passing the same parameter multiple times.

Solution using Explicit Argument Indexing

According to the documentation for fmt.Printf and related functions, you can use explicit argument indexes to format the nth argument:

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)
}
Copy after login

In the format string, %[1]v refers to the first argument, s.

Example

Here's an example using this approach:

package main

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

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

By using explicit argument indexes, you can reference the same parameter multiple times without passing it separately.

The above is the detailed content of How can I reference parameters 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template