英文:
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 < 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论