Go语言:缺乏contains方法的设计理由

huangapple go评论87阅读模式
英文:

go-lang: lack of contains method design-justification

问题

在浏览包含方法时,我遇到了以下的问答:

contains-method-for-a-slice

在这个问答中,一再提到这个方法实现起来非常简单。我不明白的是,如果实现起来如此容易,并且考虑到DRY是一种流行的软件原则,并且大多数现代语言都实现了这个方法,那么在排除这样一个简单方法的背后可能涉及到什么样的设计理念?

英文:

while browsing for a contains method, I came across the following Q&A

contains-method-for-a-slice

It is said time and again in this Q&A that the method is really trivial to implement. What I don't understand is, if it were so easy to implement, and seeing how DRY is a popular software principle && and most modern languages implement said method , what sort of design reasoning could be involved behind the exclusion of such a simple method?

答案1

得分: 4

实现的复杂程度取决于实现的范围。如果你知道如何比较每个值,那么实现起来是很简单的。应用程序代码通常知道如何比较该应用程序中使用的类型。但是对于任意类型的一般情况来说,实现起来并不简单,而这正是语言和标准库所面临的情况。

英文:

The triviality of the implementation depends on the scope of the implementation. It is trivial to implement when you know how to compare each value. Application code usually knows how to compare the types used in that application. But it is not trivial to implement in the general case for arbitrary types, and that is the situation for the language and standard library.

答案2

得分: 3

判断一个切片是否包含某个对象是一个O(n)的操作,其中n是切片的长度。即使语言提供了一个执行此操作的函数,这个操作的时间复杂度也不会改变。如果你的代码经常需要检查切片是否包含某个值,你应该重新评估你选择的数据结构;在这种情况下,使用映射(map)通常更好。为什么标准库应该包含鼓励你使用错误数据结构的函数呢?

英文:

Figuring out if a slice contains a certain object is an O(n) operation where n is the length of the slice. This would not change if the language provided a function to do this. If your code relies on frequently checking if a slice contains a certain value, you should reevaluate your choice of data structures; a map is usually better in these kind of cases. Why should the standard library include functions that encourage you to use the wrong data structure for the task you have?

huangapple
  • 本文由 发表于 2014年12月19日 00:45:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/27551584.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定