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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度