dpa0760 2015-09-09 15:24
浏览 14

如何在Go中检查动态字符串格式错误?

I have a Go program which accepts and uses format strings supplied by the user at runtime. The specification for these would be something like "a format string which accepts three ints", etc.

If the user gives me a string which doesn't meet my specification, I would like to return/output an error. I don't believe there is a simple way to do this with the fmt library: is this correct? How should I do this?

I can think of three potential approaches, but I have problems with all of them:

  1. Call fmt.Sprintf(inputFmt, args...) and search it for the "!%" substrings that are produced when the formatter encounters a problem. This doesn't work if the user actually wants a string with "!%" somewhere in it. I think the likelihood of this is small for my application, but I'd really prefer not to make this restriction if I didn't have to.

  2. Write code that inspects the input string prior to formatting to see if it complies with my specification. For the example above, I'd check if there were exactly three valid integer verbs (complete with checking all the flags that those verbs could take). Looking at doPrintf() in fmt/print.go, this seems like a lot of work.

  3. Don't explicitly check that formatting succeeded, but report an error later when the misformatted string is unsuccessfully used. (E.g. the file %!s(int=1).dat%!(EXTRA int=2, int=3) does not exist or is misformatted). I think this type of error message might be confusing to non Go programmers who use my program and will also not work in all cases where a format string is needed.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥500 52810做蓝牙接受端
    • ¥15 基于PLC的三轴机械手程序
    • ¥15 多址通信方式的抗噪声性能和系统容量对比
    • ¥15 winform的chart曲线生成时有凸起
    • ¥15 msix packaging tool打包问题
    • ¥15 finalshell节点的搭建代码和那个端口代码教程
    • ¥15 Centos / PETSc / PETGEM
    • ¥15 centos7.9 IPv6端口telnet和端口监控问题
    • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
    • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录