• 字符串字面量

Go 支持使用原始字符串字面值,可以使用反引号来表示原生字符串。在需要转义的场景下,我们应该尽量使用使用反引号表示字符串,避免转义。

// Bad
wantError := "unknown name:\"test\""

// Good
wantError := `unknown error:"test"`
  • 不要使用字符串表示 list 和 map 结构。
// Bad
var Receivers = "tom,jerry,spike"

// Good
var Receivers = []string{"tom","jerry","spike"}
  • 字符串拼接

行内字符串拼接时,出于性能的考虑,待拼接字符串数量较少(<=3)且不涉及类型转换时,使用运算符 + 而非fmt.Sprintf()

// Bad
str := fmt.Sprintf("rsp msg is %v", code)

// Good
str := "rsp msg is " + code

当待拼接字符串数量较多时(>3)或存在类型转换时,使用 fmt.Sprintf()

// Bad
str := "rsp code is " + strconv.Itoa(code) + " and msg is" + msg

// Good
str :=  fmt.Sprintf("rsp code is %v and msg is %v", code, msg)
powered by Gitbook该文章修订时间: 2024-03-22 15:30:00

results matching ""

    No results matching ""