News for hackers. Stuff that matters.
Re:Things Go needs more than generics by phplovesong on Monday October 04, 2021 @02:07AM (#28743566)
Agreed o the Enum part. It kind of sucks that if i expose a package level const (like a enum-ish thing) its not enforced by the compiler.

    package options

    const (
        OK = iota
        WARNING
        FATAL
    )
Later in the code

    import (
        "package/options"
    )


    func main() {
        ok := options.OK // iota value 1
        useOption(ok) // OK
        useOption(1) // ALSO OK
    }

I should be able to enforce that only values from the exposed options can be used on a type level.
Re:Things Go needs more than generics by mariusor on Monday October 04, 2021 @03:50AM (#28744189)
But you can do that if you create a type for the enum values :

    type errorLevel int

    const (
        OK errorLevel = iota
        WARNING
        FATAL
    )
 ...
Re:Things Go needs more than generics by marcus_holmes on Monday October 04, 2021 @05:09AM (#28744641)
The compiler doesn't enforce only those values being acceptable.

I can do:

    myerrorlevel := errorlevel(3458967478)
and the compiler won't complain at all.

It would be good if there was some way of specifying that this type can only accept these values.

Thinking about it, it's the same as nil-safe types - being able to specify to the compiler that this type cannot accept a nil value.

Re:Things Go needs more than generics by mbnull on Monday October 04, 2021 @07:22AM (#28745322)
unless errorlevel is exported as ErrorLevel you can only do so inside the declaring package.
Re:Things Go needs more than generics by mariusor on Monday October 04, 2021 @08:11AM (#28745656)
Indeed, that was the idea behind keeping it unexported.

From an external package you can only access the explicit values and the functions that accept them as parameters. The type is opaque for the developer.

Re:Things Go needs more than generics by marcus_holmes on Monday October 04, 2021 @09:14AM (#28746264)
Yeah, ok, fair point. That kinda works, but enums would be better