dongwei8729 2013-06-20 18:41
浏览 80
已采纳

最佳做法,如何初始化自定义类型?

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
}
  • 写回答

1条回答 默认 最新

  • duanran8648 2013-06-20 18:50
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?