var organisations []Organisation creates an array of Organisation. But how may "container/list" create a list of Organisation (and not of anything?)

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

var organisations []Organisation creates an array of Organisation. But how may "container/list" create a list of Organisation (and not of anything?)

问题

第一种选择:使用切片

var organisations []*Organisation

for _, org := range ... { // 预计有2到10,000个项目
    organisations = append(organisations, org)
}
  • 我有强类型,

第二种选择:使用container/list

import "container/list"

organisations := list.New()

for _, org := range ... {
    organisations.MoveToBack(org) // 被拒绝:无法将类型*Organisation用作类型*Element
}
  • 它根本没有类型。如果我将这个列表发送给另一个函数,接收者将不会信任其内容,因为从其声明来看,它被填充了任何东西。

我该如何声明一个Organisation的列表?就像我可以创建一个它们的数组一样?

我的尝试被拒绝了,我不明白为什么。

英文:

First choice: using slice

var organisations []*Organisation

for _, org := range ... { // 2 to 10 000 items expected
    organisations = append(organisations, org)
}
  • I have strong typing,

Second choice: using container/list

import "container/list"

organisations := list.New()

for _, org := range ... {
    organisations.MoveToBack(org) // Refused: cannot use type *Organisation as the type *Element
}
  • it has no typing at all. If I send this list to another function, as it is, the receiver won't trust its content, as from its declaration it is filled with anything.

How may I declare a list of Organisation? Like I can create an array of them?

May attempt is refused, and I don't understand why.

答案1

得分: 2

你为什么认为使用切片会很慢?你有进行过测量吗?

切片插入,特别是如果你预先分配了切片的大小,是常数时间的:

organizations := make([]*Organization, 0, len(...))

在这之后,每次切片追加操作只是在数组中设置一个值。

即使你没有预先分配大小,切片也会根据需要进行动态调整和复制,但不是每个元素都会进行复制。

如果你使用列表,你会失去随机访问的能力,但你可以以常数时间高效地在列表的任意位置插入元素。

所以,根据你在构建之后的使用计划选择合适的解决方案。

英文:

Why do you think using slices would be slow? Have you measured?

Slice insertion, especially if you pre-allocate the slice, is constant-time:

organizations:=make([]*Organization,0,len(...))

After this, each slice-append is simply setting a value in an array.

Even if you do not pre-allocate it, the slice will be dynamically resized and copied as necessary, but not for each element.

If you use a list, you'll lose random access, but you can efficiently insert anywhere in the list in constant time.

So, pick the solution based on how you're planning to use it after construction.

huangapple
  • 本文由 发表于 2023年6月26日 20:10:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76556561.html
匿名

发表评论

匿名网友

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

确定