GO语言之基础数据类型__字符串格式化

一,格式化在逻辑中非常常用。使用格式化函数,要注意写法:

  fmt.Sprintf(格式化样式, 参数列表…)

    格式化样式:字符串形式,格式化动词以%开头。

    参数列表:多个参数以逗号分隔,个数必须与格式化样式中的个数一一对应,否则运行时会报错

  在GO语言中,格式化的命名延续C语言的风格:

var progress = 2
var target = 8
// 两参数格式化
title := fmt.Sprintf("已采集%d个药草, 还需要%d个完成任务", progress, target)
fmt.Println(title)
pi := 3.14159
// 按数值本身的格式输出
variant := fmt.Sprintf("%v %v %v", "月球基地", pi, true)
fmt.Println(variant)
// 匿名结构体声明, 并赋予初值
profile := &struct {
    Name string
    HP   int
}{
    Name: "rat",
    HP:   150,
}
fmt.Printf("使用'%%+v' %+v
", profile)
fmt.Printf("使用'%%#v' %#v
", profile)
fmt.Printf("使用'%%T' %T
", profile)

/*
已采集2个药草, 还需要8个完成任务
"月球基地" 3.14159 true
使用'%+v' &{Name:rat HP:150}
使用'%#v' &struct { Name string; HP int }{Name:"rat", HP:150}
使用'%T' *struct { Name string; HP int }C语言中, 使用%d代表整型参数
*/

  字符串格式化常用的动词和功能:

  

    

原文地址:https://www.cnblogs.com/laogao123/p/10895479.html