Type-safe enums?

651 views
Skip to first unread message

levi

unread,
Nov 27, 2009, 6:08:50 PM11/27/09
to golang-nuts
I seem to be unable to define a type-safe enumeration in Go. I tried:


package main

import "fmt"

type Ty1 int

const (
A Ty1 = iota;
B;
C
)

func f(x Ty1) {
fmt.Println(x)
}


Applying f to A, B, or C works fine, but unfortunately the compiler
accepts every int for f, which is not what I want. I rather want f to
be defined only for A,B,C. How would one do this in Go?

Thanks,
Levi

Ostsol

unread,
Nov 27, 2009, 8:39:30 PM11/27/09
to golang-nuts
What platform are you running Go on? On mine (Linux amd64) I can't
get Go to compile when I try, for example:

func main () {
var a int = 4;
f (4)

Ian Lance Taylor

unread,
Nov 27, 2009, 8:43:13 PM11/27/09
to levi, golang-nuts
Unfortunately, there is no way to prevent code from passing an untyped
constant to f. An untyped constant may take on any type, including
the type Ty1. Variables which do not have type Ty1 will not work, but
constants will.

This handling of untyped constants is normally a feature, but this is
a case where it is undesirable.

Ian

levi

unread,
Nov 28, 2009, 10:09:54 AM11/28/09
to golang-nuts
On Nov 28, 2:43 am, Ian Lance Taylor <i...@google.com> wrote:
Thanks. Did you consider algebraic datatypes [1] for Go? They unify
structs, enums and distriminated unions [2].

Cheers,
Levi

---
[1] http://en.wikipedia.org/wiki/Algebraic_data_type
[2] http://book.realworldhaskell.org/read/defining-types-streamlining-functions.html#deftypes.adt.comp
Message has been deleted

Ian Lance Taylor

unread,
Nov 28, 2009, 8:40:32 PM11/28/09
to levi, golang-nuts
levi <greensp...@googlemail.com> writes:

> Thanks. Did you consider algebraic datatypes [1] for Go? They unify
> structs, enums and distriminated unions [2].

They are being considered, yes.

Ian

roger peppe

unread,
Nov 30, 2009, 6:17:47 AM11/30/09
to inspector_jouve, golang-nuts
2009/11/28 inspector_jouve <kaush...@gmail.com>:
> Problem would be solved if language treated aggregates of constants as
> constants - in this case you could write
>
> type Ty1 struct { value int }
> const (
>    A Ty1 = T1{iota};
>    B;
>    C
> )
>
> Right now, compiler complains that T1{iota} is not a constant
> expression.

i think this would be a useful enhancement to the language.
Reply all
Reply to author
Forward
Message has been deleted
0 new messages