TrimRight()和TrimSuffix()字面上都是删除字符串右侧的字符,但是二者还是有很大的不同的,先看一下我写的Bug吧,用来当作错误示范。
期望的功能:有域名test.com,有全限定域名full.info.test.com. 我需要把域名从fqdn中去除,得到主机名,使用TrimRight函数实现的代码如下:
func main() {
fqdn := "full.info.test.com."
host := strings.TrimRight(fqdn, ".test.com.")
fmt.Printf("fqdn:%v\n",[]byte(fqdn))
fmt.Printf("fqdn:%v\n",fqdn)
fmt.Printf("host:%v\n",[]byte(host))
fmt.Printf("host:%v\n",host)
}输出结果:
fqdn:[102 117 108 108 46 105 110 102 111 46 116 101 115 116 46 99 111 109 46] fqdn:full.info.test.com. host:[102 117 108 108 46 105 110 102] host:full.inf
可以看到,这段代码并没有按我所期望的运行,输出了“host:full.inf“,而不是”host:full.info“
到pkg.go.dev看源码,发现TrimRight 返回字符串 s 的一个切片,其中包含在 cutset 中的所有尾随 Unicode 代码点都被删除。
// TrimRight returns a slice of the string s, with all trailing
// Unicode code points contained in cutset removed.
//
// To remove a suffix, use TrimSuffix instead.
func TrimRight(s, cutset string) string {
if s == "" || cutset == "" {
return s
}
if len(cutset) == 1 && cutset[0] < utf8.RuneSelf {
return trimRightByte(s, cutset[0])
}
if as, ok := makeASCIISet(cutset); ok {
return trimRightASCII(s, &as)
}
return trimRightUnicode(s, cutset)
}所以,删除后缀一定要用TrimSuffix()而不是TrimRight()