英文:
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"))
}
英文:
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"))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论