golang基础小记(20)——将格式化字符串作为函数参数

直接上简单实例:

package main

import "fmt"

func formatAsArgs(format string, a ...interface{}) {
	s := fmt.Sprintf(format, a...)
	fmt.Println(s)
}

func main() {
	name := "小明"
	id := 10086
	formatAsArgs("name:%s, id:%d", name, id) // name:小明, id:10086
	formatAsArgs("name, id") // name, id
}

参数a ...interface{}使得函数可以接收0个及以上的参数,使得函数既能接收普通字符串,也能接收格式化字符串。

猜你喜欢

转载自blog.csdn.net/m0_37710023/article/details/107917747