go一些数据类型转换 sort、strconv包
//maxValue and minValue
math.MaxInt64
math.MinInt64
?
?
//Sort a map by key or value
m := map[string]int{"Alice": 2, "Cecil": 1, "Bob": 3}
?
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
?
for _, k := range keys {
fmt.Println(k, m[k])
}
?
切片排序
sort.Ints([]int)
sort.Strings(string)
sort.Float64s(float64)
?
//sort slice,不稳定,稳定的话用SliceStake
func Slice(x any, less func(i, j int) bool)
?
func main() {
people := []struct {
Name string
Age int
}{
{"Gopher", 7},
{"Alice", 55},
{"Vera", 24},
{"Bob", 75},
}
sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name })
fmt.Println("By name:", people)
?
sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age })
fmt.Println("By age:", people)
}
常见的类型转换
strings.Join(s1 []string, sep string) //用sep把s1中的所有元素链接起来
?
strconv.Itoa(i int)string //把一个整数i转成字符串
strconv.Atoi(str string)int //把一个字符串转成整数
?
//parse: convert string to outher types
b, err := strconv.ParseBool("true") // result: true, bool
f, err := strconv.ParseFloat("3.14", 64) // result: 3.14, float64
i, err := strconv.ParseInt("-18", 10, 64) // result: -18, int64
u, err := strconv.ParseUint("18", 10, 64) // result: 18, int64
?
//format: convert others to string
strconv.FormatInt(123, 10) // 123 int-->string 10表示十进制
strconv.Itoa(123) // 123 十进制int-->string
strconv.FormatFloat(3.14, 'f', 6, 64) // 3.140000 float-->string 6:保留6位 64:float64
?
?