douxu2467 2018-10-27 01:33
浏览 48

如何在Go中定义用户定义类型的常量值?

I am implementing a bit-vector in Go:

// A bit vector uses a slice of unsigned integer values or “words,”
// each bit of which represents an element of the set.
// The set contains i if the ith bit is set.
// The following program demonstrates a simple bit vector type with these methods.
type IntSet struct {
    words []uint64 //uint64 is important because we need control over number and value of bits
}

I have defined several methods (e.g. membership test, adding or removing elements, set operations like union, intersection etc.) on it which all have a pointer receiver. Here is one such method:

// Has returns true if the given integer is in the set, false otherwise
func (this *IntSet) Has(m int) bool {
   // details omitted for brevity
}

Now, I need to return an empty set that is a true constant, so that I can use the same constant every time I need to refer to an IntSet that contains no elements. One way is to return something like &IntSet{}, but I see two disadvantages:

  • Every time an empty set is to be returned, a new value needs to be allocated.
  • The returned value is not really constant since it can be modified by the callers.

How do you define a null set that does not have these limitations?

  • 写回答

1条回答 默认 最新

  • dongtanjian9310 2018-10-27 02:08
    关注

    If you read https://golang.org/ref/spec#Constants you see that constants are limited to basic types. A struct or a slice or array will not work as a constant.

    I think that the best you can do is to make a function that returns a copy of an internal empty set. If callers modify it, that isn't something you can fix.

    Actually modifying it would be difficult for them since the words inside the IntSet are lowercase and therefore private. If you added a value next to words like mut bool you could add a if mut check to every method that changes the IntSet. If it isn't mutable, return an error or panic.

    With that, you could keep users from modifying constant, non-mutable IntSet values.

    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀