Golang 中的字符串:常见错误和优秀实践( 二 )

输出:
char at 0 index, has type uint8 and value is 226value is 10084 type is int32value is 65509 type is int32value is 37 type is int32value is 8230 type is int32value is 8230 type is int32value is 38 type is int32value is 42 type is int32在对字符串进行迭代时 , 还要注意变量中可能存在的非 UTF8 字符,如果 Golang 无法将其理解为 UTF8 , 则会使用 unicode 替换而非实际值 。
5. 字符串平等在 Golang 中,我们总是可以使用 == 来检查简单的字符串是否相等,但如果我们的变量存在隐藏点,则应在比较两个字符串变量之前使用 unicode 规范包将其规范化:
func main() { cafe1 := "Café" cafe2 := "Cafeu0301" normalizeCafe1 := norm.NFC.String(cafe1) normalizeCafe2 := norm.NFC.String(cafe2) fmt.Println(cafe1 == cafe2) fmt.Println(normalizeCafe1 == normalizeCafe2)}6. 高效字符串构建使用“+”连接大量字符串的效率可能非常低 。使用 strings.Builder 是高效构建字符串的最佳方法之一:
func main() { sb := strings.Builder{} for i := 0; i < 1000; i++ {  sb.WriteString("hello ") } result := sb.String() fmt.Println(result)}与传统的 + 连接方法相比,这种方法速度更快 , 内存消耗更少,而且可以避免创建不必要的中间字符串 。我们还可以使用 bytes.Buffer 软件包来实现这一目标 。
总结

  • 字符串的默认值是""
  • len 和 RuneCountIntString 函数具有不同的行为
  • 我们应该小心 for 循环和字符串
  • 字符串相等是我们需要更精确的地方




推荐阅读