Go字符串格式化只填充部分参数。

huangapple go评论73阅读模式
英文:

Go string format fill only part of the arguments

问题

我有一个用于调用外部 API 的标准字符串格式,例如 https://%s?client=%s&password=%s

这是请求的第一个 %s 终点,它取决于业务逻辑。而我可以事先确定客户端和密码。

func getApiUrl(clientId int) string {
    urlFormat := "https://%s?client=%s&password=%s"
    clientname, clientpass := getByClientId(clientId)
    return fmt.Sprintf(urlFormat, _, clientname, clientpass) // https://%s?client=clientname&password=clientpass
}

我想写一个类似的函数来填充一些参数。当然,以这种形式是无法工作的。

英文:

I have a standard string format for calling an external api. e.g. https://%s?client=%s&password=%s.

Here is the first %s endpoint of the request which depends on the business logic. While I can always determine the client and password in advance.

func getApiUrl(clientId int) string {
	urlFormat := "https://%s?client=%s&password=%s"
	clientname, clientpass := getByClientId(clientId)
	return fmt.Sprintf(urlFormat, _, clientname, clientpass) // https://%s?client=clientname&password=clientpass
}

I would like to write something like a function that will fill in some of the parameters. In this form, it does not work, of course.

答案1

得分: 1

你可以在占位符中使用"%s"

package main

import "fmt"

func getByClientId(clientId int) (string, string) {
	return "user", "password"
}

func getApiUrl(clientId int) string {
	urlFormat := "https://%s?client=%s&password=%s"
	clientname, clientpass := getByClientId(clientId)
	return fmt.Sprintf(urlFormat, "%s", clientname, clientpass) // https://%s?client=clientname&password=clientpass
}

func main() {
	userPasswordFilled := getApiUrl(3)
	fmt.Println(fmt.Sprintf(userPasswordFilled, "example.com"))
}

Go Playground

英文:

You can use "%s" in the placeholder.

package main

import "fmt"

func getByClientId(clientId int) (string, string) {
	return "user", "password"
}

func getApiUrl(clientId int) string {
	urlFormat := "https://%s?client=%s&password=%s"
	clientname, clientpass := getByClientId(clientId)
	return fmt.Sprintf(urlFormat, "%s", clientname, clientpass) // https://%s?client=clientname&password=clientpass
}

func main() {
	userPasswordFilled := getApiUrl(3)
	fmt.Println(fmt.Sprintf(userPasswordFilled, "example.com"))
}

Go Playground

huangapple
  • 本文由 发表于 2022年10月6日 15:57:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/73970361.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定