drsh30452 2016-01-27 16:45
浏览 163


I have a Golang program that reads a string parameter from command line and passes it to the fmt.Sprintf function. Let's say tmp_str is the target string from command line.

package main

import "fmt"

func main() {
    tmp_str := "hello %s"
    str := fmt.Sprintf(tmp_str, "world")

In some cases, the program will pass a completed string like "Hello Friends", instead of a string template.. The program would panic and return:

Hello Friends%!(EXTRA string=world)

So, how to ignore the extra fields for fmt.Sprintf?

  • 写回答

5条回答 默认 最新

  • dongpaipu8394 2016-01-27 17:46

    Yes you can do it, by slicing the arguments you pass to the variadic Sprintf function:

    func TruncatingSprintf(str string, args ...interface{}) (string, error) {
        n := strings.Count(str, "%s")
        if n > len(args) {
            return "", errors.New("Unexpected string:" + str)
        return fmt.Sprintf(str, args[:n]...), nil
    func main() {
        tmp_str := "hello %s %s %s"         // don't hesitate to add many %s here
        str, err := TruncatingSprintf(tmp_str, "world") // or many arguments here
        if err != nil {

    Demonstration 1

    Demonstration 2 (a different version outputting even when there's more %s than arguments)

    But you don't usually use dynamic formatted strings, this isn't secure and if you want to accept any string, you should also adapt this code to no choke on %%s. If you venture this far, then you should probably have a look at templates (which would let you use named strings, and thus the missing one wouldn't have to be the last one).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥500 亚马逊 COOKIE我如何才能实现 登录一个亚马逊账户 下发新 COOKIE ..我使用下发新COOKIE 导入ADS 指纹浏览器登录,我把账户密码 修改过后,原来下发新COOKIE 不会失效的方式
  • ¥20 玩游戏gpu和cpu利用率特别低,玩游戏卡顿
  • ¥25 oracle中的正则匹配
  • ¥15 关于#vscode#的问题:把软件卸载不会再出现蓝屏
  • ¥15 vimplus出现的错误
  • ¥15 usb无线网卡转typec口
  • ¥30 怎么使用AVL fire ESE软件自带的优化模式来优化设计Soot和NOx?
  • ¥15 Ubuntu20.04.4.LTS系统如何下载安装VirtualBox虚拟机?
  • ¥15 如何用QDomDocument读取内容为空格的xml数据
  • ¥15 请阅读下面代码,帮我修改下代码