米琪卡哇伊
省略无效符文的简单版本可能如下所示:func forceASCII(s string) string { rs := make([]rune, 0, len(s)) for _, r := range s { if r <= 127 { rs = append(rs, r) } } return string(rs)}// forceASCII("Hello, World!") // => "Hello, World!"// forceASCII("Hello, 世界!") // => "Hello, !"// forceASCII("Привет") // => ""但是,如果目标 UTF-8 字符串包含 ASCII 字符范围之外的任何字符,您想要特殊行为怎么办[0,127]?您可以编写一个函数来处理各种情况,方法是提取一个采用无效 ASCII 符文并返回字符串替换或错误的函数参数。例如(去游乐场):func forceASCII(s string, replacer func(rune) (string, error)) (string, error) { rs := make([]rune, 0, len(s)) for _, r := range s { if r <= 127 { rs = append(rs, r) } else { replacement, err := replacer(r) if err != nil { return "", err } rs = append(rs, []rune(replacement)...) } } return string(rs), nil}func main() { replacers := []func(r rune) (string, error){ // omit invalid runes func(_ rune) (string, error) { return "", nil }, // replace with question marks func(_ rune) (string, error) { return "?", nil }, // abort with error */ func(r rune) (string, error) { return "", fmt.Errorf("invalid rune 0x%x", r) }, } ss := []string{"Hello, World!", "Hello, 世界!"} for _, s := range ss { for _, r := range replacers { ascii, err := forceASCII(s, r) fmt.Printf("OK: %q → %q, err=%v\n", s, ascii, err) } } // OK: "Hello, World!" → "Hello, World!", err=<nil> // OK: "Hello, World!" → "Hello, World!", err=<nil> // OK: "Hello, World!" → "Hello, World!", err=<nil> // OK: "Hello, 世界!" → "Hello, !", err=<nil> // OK: "Hello, 世界!" → "Hello, ??!", err=<nil> // OK: "Hello, 世界!" → "", err=invalid rune 0x4e16}