Go strings.TrimLeft() strings.TrimPrefix().md

今天在调试时, 有个函数的返回的结果很奇怪, 和预期的输入差了一个字符, 而review代码时却没发现什么问题, 后面各种加logger.Debugf()才发现是strings.TrimLeft()这个函数表现得和自己的预期不一致, 从函数名上看这个是删除字符串左边的字符串, 但是传入一个带:的字符串去调用,发现:后面的字符也被Trim了, 于是去Github issues上搜了下这个问题https://github.com/golang/go/issues/19371, 有人也感觉奇怪也反馈过, 解释是 The second argument to Trim is a set of code points, not a prefix/suffix. , 于是去翻了下文档, 确实是这样的.

TrimLeft returns a slice of the string s with all leading Unicode code points contained in cutset removed.

问题复现代码(go 1.8) https://play.golang.org/p/YtmVQIf2_i:

package main

import (
"fmt"
"strings"
)

func main() {
str := "friends:d15fc7bb-1e67-11e7-b8a5-00163e008796"
prefix1 := "friends:"
prefix2 := "friends"
fmt.Printf("%v\n", strings.TrimLeft(str, prefix1))
fmt.Printf("%v\n", strings.TrimPrefix(str, prefix1))
fmt.Printf("%v\n", strings.TrimLeft(str, prefix2))
fmt.Printf("%v\n", strings.TrimPrefix(str, prefix2))
}

output:

15fc7bb-1e67-11e7-b8a5-00163e008796
d15fc7bb-1e67-11e7-b8a5-00163e008796
:d15fc7bb-1e67-11e7-b8a5-00163e008796
:d15fc7bb-1e67-11e7-b8a5-00163e008796