Golang:在字符串的类型别名上使用string.join
发布时间:2020-12-16 09:24:47 所属栏目:大数据 来源:网络整理
导读:我有一个字符串类型的别名 键入SpecialScopes字符串 我想使用strings.Join函数加入这种类型的数组 func MergeScopes(scopes ...SpecialScopes) SpecialScopes { return strings.Join(scopes,",")} 但是上面我得到了错误 cannot use scopes (type []SpecialSc
我有一个字符串类型的别名
键入SpecialScopes字符串 我想使用strings.Join函数加入这种类型的数组 func MergeScopes(scopes ...SpecialScopes) SpecialScopes { return strings.Join(scopes,",") } 但是上面我得到了错误 cannot use scopes (type []SpecialScopes) as type []string in argument to strings.Join cannot use strings.Join(scopes,") (type string) as type SpecialScopes in return argument 有没有办法让golang意识到SpecialScopes只是字符串的另一个名称,并在其上执行连接功能? 更新1: func MergeScopes(scopes ...SpecialScopes) SpecialScopes { var s []string for _,scope := range scopes { s = append(s,string(scope)) } return SpecialScopes(strings.Join(s,")) } 解决方法
这是大多数不使用不安全的最快方式.
func MergeScopes(scopes ...SpecialScopes) SpecialScopes { if len(scopes) == 0 { return "" } var ( sep = []byte(",") // preallocate for len(sep) + assume at least 1 character out = make([]byte,(1+len(sep))*len(scopes)) ) for _,s := range scopes { out = append(out,s...) out = append(out,sep...) } return SpecialScopes(out[:len(out)-len(sep)]) } 基准代码:https://play.golang.org/p/DrB8nM-6ws ━? go test -benchmem -bench=. -v -benchtime=2s testing: warning: no tests to run BenchmarkUnsafe-8 30000000 109 ns/op 32 B/op 2 allocs/op BenchmarkBuffer-8 20000000 255 ns/op 128 B/op 2 allocs/op BenchmarkCopy-8 10000000 233 ns/op 112 B/op 3 allocs/op BenchmarkConcat-8 30000000 112 ns/op 32 B/op 2 allocs/op (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |