登录
首页 >  Golang >  Go问答

为什么 Go 中“Split”不是“string”类型的成员函数?

来源:stackoverflow

时间:2024-04-17 21:09:35 387浏览 收藏

今天golang学习网给大家带来了《为什么 Go 中“Split”不是“string”类型的成员函数?》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~

问题内容

当您想要使用不同语言的特定分隔符分割字符串时,以下是一些片段:

# 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
}

这样设计的原因是什么?


解决方案


正如你所看到的,“split”在python和javascript中是字符串类型的成员函数,但在golang中不是。

从一开始似乎就是这样:commit 729bc5c, Sept 2008, for Go1 是第一个提到 string split() 函数的提交。

基本的字符串实用程序。

这些函数被视为“实用程序”,而不是 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 {

您可以在func LookPath(file string) (string, *os.Error) {中的commit 5eae3b2, April 2009中看到它的第一次使用

相同的方法用于字节与字节:commit 7893322, June 2009; Go1,与similar Split() function

添加一个类似于 strings 包的 bytes 包。

总体思路是:您可以更改该效用函数而不更改值类型本身。
请参阅commit 30533d6, June 2009

更改 strings.splitbytes.split 以采用最大子字符串 count 参数。

func split(s, sep []byte, n int) [][]byte

更加剧烈的演变:commit ebb1566, June 2011

strings.split:默认拆分全部。
将 split 的签名更改为没有计数(假设完全拆分),并将现有的带有计数的 split 重命名为 splitn

另一个想法是继续使用 string,同时在不需要这些实用函数时可能删除对它们的依赖关系(如 commit 35ace1d, Nov. 2009 中所示:“删除对 strconvstrings 的依赖关系”)

它还允许添加更多相关函数,而无需触及字符串本身。
请参阅 commit 5d436b9, Nov. 2009:lines := strings.splitafter(text, "\n", 0),它使用 split()

另一个优点:您可以独立于 string 本身来优化这些函数,允许用 strings.split() 替换重复的“split”函数。
查看commit f388119, March 2013, Go 1.1

go/printer:使用 strings.split 而不是专用代码

使用更快的字符串包,专用代码和 strings.split 之间的区别在于噪音:

benchmark         old ns/op    new ns/op    delta
benchmarkprint     16724291     16686729   -0.22%

相反的情况也是如此:用更简单的代码替换 strings.split,如 commit d0c9b40, Sept. 2015, Go 1.6

mime:删除字解码中的分配。

这通过使用简单的前缀/后缀检查和一些自定义切片替换对 strings.split 的调用来修复 (*worddecoder).decode 中的 todo

基准测试结果:

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 相同的想法)

今天关于《为什么 Go 中“Split”不是“string”类型的成员函数?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>