majidarif
majidarif

Reputation: 19985

Golang map or struct to add or remove from list

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?

Upvotes: 0

Views: 366

Answers (1)

resilva87
resilva87

Reputation: 3465

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

Upvotes: 2

Related Questions