1. 程式人生 > 其它 >go一些資料型別轉換 sort、strconv包

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