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

如何忽略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 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据