当您想要使用不同语言的特定分隔符分割字符串时,以下是一些片段:
# python
s = 'a,b,c,d,e'
tokens = s.split(',')
// javascript
let s = 'a,b,c,d,e'
let tokens = s.split(',')
// go
s := "a,b,c,d,e"
tokens := strings.Split(s, ",")
如您所见,“split”在Python和Javascript中是字符串类型的成员函数,但在Go中不是。 我想知道为什么,看起来像CPP中的STL,为什么操作类型实例的函数不是该类型的成员函数,在Go中似乎很容易实现它们,例如:
// go
func (s *string) Split(d string) []string {
// here goes the code to split s with d given
}
这样设计的原因是什么?
最佳答案
As you can see, "split" is a member function of type string in python and javascript, but not in golang.
似乎从一开始就是这样:commit 729bc5c, Sept 2008, for Go1是第一个提及 string Split()
的提交功能。
rudimentary string utilities.
这些功能被视为“实用程序”,而不是 predeclared string type ' string
' itself 的一部分.
不久之后,它就被记录在commit 0f7306b, March 2009, still Go1中。
// Split returns the array representing the substrings of s separated by string sep. Adjacent
// occurrences of sep produce empty substrings. If sep is empty, it is the same as Explode.
func Split(s, sep string) []string {
您可以在 commit 5eae3b2, April 2009 中看到它的首次使用。在 func LookPath(file string) (string, *os.Error) {
同样的方法也适用于字节与字节:commit 7893322, June 2009; Go1 ,带有 similar Split() function .
add a bytes package analogous to the strings package.
总体思路是:您可以更改实用函数而不更改值类型本身。
请参阅commit 30533d6, June 2009 :
Change
strings.Split
,bytes.Split
to take a maximum substringcount
argument.func Split(s, sep []byte, n int) [][]byte
更加剧烈的演变:commit ebb1566, June 2011
strings.Split
: make the default to split all.
Change the signature of Split to have no count, assuming a full split, and rename the existingSplit
with a count toSplitN
.
另一个想法是继续使用 string
,同时可能在不需要时删除对这些实用程序函数的依赖关系(如 commit 35ace1d, Nov. 2009 :“删除对 strconv
和 strings
的依赖关系”)
它还允许添加更多相关函数,而无需触及字符串本身。
请参阅commit 5d436b9, Nov. 2009 : 行 := strings.SplitAfter(text, "\n", 0)
,它使用 Split()
.
另一个优点:您可以独立于 string
来优化这些功能本身,允许将重复的“Split”函数替换为 strings.Split()
.
请参阅commit f388119, March 2013, Go 1.1
go/printer
: usestrings.Split
instead of specialized codeWith the faster strings package, the difference between the specialized code and strings.Split is in the noise:
benchmark old ns/op new ns/op delta BenchmarkPrint 16724291 16686729 -0.22%
相反的情况也是如此:用更简单的代码替换 strings.Split,如commit d0c9b40, Sept. 2015, Go 1.6
mime: Remove an allocation in word decoding.
This fixes a
TODO
in(*WordDecoder).Decode
by replacing a call tostrings.Split
with simple prefix/suffix checking and some custom slicing.Benchmark results:
benchmark old ns/op new ns/op delta BenchmarkQEncodeWord-8 740 693 -6.35% BenchmarkQDecodeWord-8 1291 727 -43.69% BenchmarkQDecodeHeader-8 1194 767 -35.76%
(与 commit ecff943, Sept. 2017, Go 1.11 中的想法相同)
关于algorithm - 为什么 "Split"不是 Go 中 "string"类型的成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52575282/