Kedar Mhaswade
Kedar Mhaswade

Reputation: 4695

How to Define a Constant Value of a User-defined Type in 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:

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

Upvotes: 0

Views: 627

Answers (1)

Zan Lynx
Zan Lynx

Reputation: 54325

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.

Upvotes: 2

Related Questions