我在编写demo时,刚遇见个小问题一直不明白,请求各位解答一下。代码如下:
```
package main
import (
"fmt"
)
func MySprintf(tag string, format string, v ...interface{}) {
msg := fmt.Sprintf(format, v)
fmt.Println("msg: " + msg)
fmt.Println(tag + ": " + msg)
}
func main() {
v := fmt.Sprintf("%s is bigger than %s", "beijing", "shanghai")
fmt.Println("value: " + v)
MySprintf("main/MySprintf", "%s is bigger than %s", "beijing", "shanghai")
}
```
执行结果:
```
value: beijing is bigger than shanghai
msg: [beijing shanghai] is bigger than %!s(MISSING)
main/MySprintf: [beijing shanghai] is bigger than %!s(MISSING)
```
“beijing”和“shanghai”明明是两个变参,怎么会替换到一个值去了?
明白了,是MySprintf里的变参如果再传到另外一个函数时,就变成slice了,这时需要再加上...就好了
```
func MySprintf(tag string, format string, v ...interface{}) {
msg := fmt.Sprintf(format, v...)//注意要传进来的是v...,不是v
fmt.Println("msg: " + msg)
fmt.Println(tag + ": " + msg)
}
```
测试正常。
```
value: beijing is bigger than shanghai
msg: beijing is bigger than shanghai
main/MySprintf: beijing is bigger than shanghai
```
#1
更多评论
楼主的意图,其实是不定个数的参数 <stfarg.h>,要用 vsprintf 函数。 据我所知在golang 1.4之前,还没有类似的函数,需要自己来处理 % 以及循环读取参数。
#2