从向量中删除元素。

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

Remove element from vector.Vector

问题

//从clients(vector.Vector)中移除cl(*client)
for i := 0; i < clients.Len(); i++ {
if cl == clients.At(i).(*client) {
clients.Delete(i)
break
}
}

有没有更简洁的方法从向量中移除一个元素?

英文:
//Remove cl (*client) from clients (vector.Vector)
for i := 0; i &lt; clients.Len(); i++ {
	if cl == clients.At(i).(*client) {
		clients.Delete(i)
		break
	}
}

Is there a shorter way to remove an element from a vector?

答案1

得分: 1

不完全是你要求的,但不要使用Vector,而是使用切片,在这里可以看到一些切片习惯用法及其(已弃用/不推荐使用的)Vector等效方法的摘要

你可以这样做:

for i, c := range clients {
    if c == client {
         clients = append(clients[:i], clients[i+1:]...)
    }
}

显然,对于自己的类型,定义一个相同的删除方法是很简单的。

英文:

Not really what you asked for, but do not use Vector, use a slice instead, see here for a summary of some slice-idioms and their (deprecated/discouraged) Vector equivalents.

You could do something like:

for i, c := range clients {
    if c == client {
         clients = append(clients[:i], clients[i+1:]...)
    }
}

And obviously it is trivial to define your own delete method for your own types which does the same.

huangapple
  • 本文由 发表于 2010年12月7日 22:02:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/4377414.html
匿名

发表评论

匿名网友

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

确定