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.

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

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类