func string_other_convert() { var err error var i int = 8 var i64 int64 = int64(i) //int转string var s string = strconv.Itoa(i) //内部调用FormatInt s = strconv.FormatInt(i64, 10) //string转int i, err = strconv.Atoi(s) //string转int64 i64, err = strconv.ParseInt(s, 10, 64) //float转string var f float64 = 8.123456789 s = strconv.FormatFloat(f, 'f', 2, 64) //保留2位小数 fmt.Println(s) //string转float f, err = strconv.ParseFloat(s, 64) //string<-->[]byte var arr []byte = []byte(s) s = string(arr) //string<-->[]rune var brr []rune = []rune(s) s = string(brr) fmt.Printf("err %v\n", err) } func string_impl() { s1 := "My name is 张三" arr := []byte(s1) brr := []rune(s1) fmt.Printf("last byte %d\n", arr[len(arr)-1]) //string可以转换为[]byte或[]rune类型 fmt.Printf("last byte %c\n", arr[len(arr)-1]) //byte或rune可以转为string fmt.Printf("last rune %d\n", brr[len(brr)-1]) fmt.Printf("last rune %c\n", brr[len(brr)-1]) L := len(s1) fmt.Printf("string len %d byte array len %d rune array len %d\n", L, len(arr), len(brr)) for _, ele := range s1 { fmt.Printf("%c ", ele) //string中的每个元素是字符 } fmt.Println() for i := 0; i < L; i++ { fmt.Printf("%c ", s1[i]) //[i]前面应该出现数组或切片,这里自动把string转成了[]byte,为什么不自动把string转成了[]rune?没有为什么,不定长度参数还会出现这个例子 } }