Robin Westerlundh
Robin Westerlundh

Reputation: 196

Best practices, How to initialize custom types?

I'm still not used to the go way of doing things. Here I have the type ClientConnectorPool that wraps a BidiMap. How should I initialize this type? So that I can add to my bidiMap afterwords? All my attempt's of doing this sames hackish and I need inspiration, can I implement some sort om make(ClientConnectorPool) function for it?

In my head it should look like this but all my solutions is like 15 lines of code to avoid nil pointer errors :D

CC = make(ClientConnectorPool)
CC.Add("foo","bar")

Code:

package main

import ()

type ClientConnectorPool struct {
    Name string
    ConnectorList BidirMap
}

func (c ClientConnectorPool) Add(key, val interface{}){
     c.ConnectorList.Add(key,val)
}


type BidirMap struct {
    left, right map[interface{}]interface{}
}

func (m BidirMap) Add(key, val interface{}) {
    if _, inleft := m.left[key]; inleft {
        delete(m.left, key)
    }
    if _, inright := m.right[val]; inright {
        delete(m.right, val)
    }
    m.left[key] = val
    m.right[val] = key
}

Upvotes: 1

Views: 170

Answers (1)

Dominik Honnef
Dominik Honnef

Reputation: 18430

You cannot define custom functions for make(). Make only works on slices, maps and channels (and custom types that have those representations).

Idiomatic Go would be to have a NewClientConnectorPool function (in the following abbreviated to NewPool) that creates and returns it.

func NewPool(name string) ClientConnectorPool {
  return ClientConnectorPool{
    Name: name,
    ConnectorList: BidirMap{
      left:  make(map[interface{}]interface{}),
      right: make(map[interface{}]interface{}),
    },
  }
}

You could also have a NewBidirMap function that wraps the creation of that struct.

I don't see where you need checks for nil though. make() won't return nil, and the rest is a simple struct literal.

Upvotes: 3

Related Questions