英文:
Golang map or struct to add or remove from list
问题
我有一个服务器,我希望每个连接都保存在一个列表中。假设:
type Connection struct {
   Id uint16
   Conn *conn.TCP
}
var connections []Connection
但是我想要删除/获取特定的连接ID,我应该使用什么?
我在考虑类似这样的方法:
func GetConnectionById(id uint16) Connection {
    for k, v := range connections {
       if v.Id == id {
          return v
       }
    }
}
有更好的方法吗?
英文:
I have a server and I wan't each connection to be saved into a list. Lets say:
type Connection struct {
   Id uint16
   Conn *conn.TCP
}
var connections []Connection
But what I wanted to remove / fetch the specific connection id? What should I use?
I was thinking of something like:
func GetConnectionById(id uint16) Connection {
    for k, v := range connections {
       if v.Id == id {
          return v
       }
    }
}
Is there a better approach?
答案1
得分: 2
为什么不通过其Id来将每个Connection在地图中进行标识?
package main
type Connection struct {
   Id uint16
   X string
}
var connections map[uint16]Connection
func main() {
	connections = make(map[uint16]Connection)
	connections[1] = Connection{}
}
英文:
Why not identify each Connection in a map by its Id?
package main
type Connection struct {
   Id uint16
   X string
}
var connections map[uint16]Connection
func main() {
	connections = make(map[uint16]Connection)
	connections[1] = Connection{}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论