drsh30452 2016-01-27 16:45
浏览 163
已采纳

如何忽略fmt.Sprintf的其他字段

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")
    fmt.Println(str)
}

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 {
            fmt.Println(err)
            return
        }
        fmt.Println(str)
    }
    

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多