将Golang中的map或struct添加或从列表中删除。

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

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{}
}

huangapple
  • 本文由 发表于 2016年3月2日 03:57:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/35732261.html
匿名

发表评论

匿名网友

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

确定