How to check whether the value is of type iota constant in Golang?

iota golang
golang convert iota to string
golang const
golang enum interface
golang enum json
golang test online
invalid constant type golang
golang enumer

I have the following type defined using iota in Golang.

type StatusType int

const (
    PENDING StatusType = iota
    APPROVED
    REJECTED
)

I want to restrict the value passed in REST-API to the StatusType. Such that the value should not exceed 0,1,2.

I do this way: first create a package named "StatusType" (inside a folder named StatusType): filename: $GOPATH/enum/StatusType/StatusType.go

package StatusType

type Int int

const (
    Pending Int = iota
    Approved
    Rejected
    end
)

func IsValid(value int) bool {
    return value < int(end)
}

and use like this ($GOPATH/enum/main.go):

package main

import (
    "enum/StatusType"
    "fmt"
)

func Test(enum StatusType.Int) {
    fmt.Println(enum) //1
}
func main() {
    Test(StatusType.Approved)

    fmt.Println(StatusType.IsValid(1))  //true
    fmt.Println(StatusType.IsValid(10)) //false
}

The StatusType package just exports what you need so there is no need to check against iota const range. Just in case you want to check, use: StatusType.IsValid() And nice thing about StatusType package is: When you want function parameter of StatusType type use StatusType.Int and it reveals that it is enumeration of type int. Like:

Test(StatusType.Approved)

Go by Example: Constants and iota, Go supports constants of character, string, boolean, and numeric values. We can use iota to simulate C's enum or #define constant. package Ref: http://blog.​golang.org/constants type Season uint8 output function for Season variable. Golang Constants Tutorial. The const declares a constant value. Constant expressions perform arithmetic with arbitrary precision. The numeric constant has no type until it’s given, such as by an explicit cast. A number can be given the type by using it in a context that requires one, such as the variable assignment or a function call.

Simply don't export StatusType (assuming you define it in package 'status'). This follow "What is an idiomatic way of representing enums in Go?":

type statusType int

const (
    PENDING statusType = iota
    APPROVED
    REJECTED
)
type StatusTyper interface {
    StatusType() statusType 
}

func(st statusType) StatusType() statusType {
    return st
}

Any external package would then refer to StatusType-like variable as status.PENDING, status.APPROVED or status.REJECTED. (the only three statusType which implement the StatusTyper interface. Caveat applies.)

4 iota enum examples · YourBasic Go, CODE EXAMPLE The iota identifier is used to enumerate constants. For an idiomatic enum implementation, create a new type and give it a String function. yourbasic.org/golang. Iota basic example. Start from one; Skip value You can use the blank identifier to skip a value in a list of constants. const ( C1 = iota + 1 _ C3  To start a list of constants at 1 instead of 0, you can use iota in an arithmetic expression. const ( C1 = iota + 1 C2 C3 ) fmt.Println(C1, C2, C3) // "1 2 3" Skip value. You can use the blank identifier to skip a value in a list of constants. const ( C1 = iota + 1 _ C3 C4 ) fmt.Println(C1, C3, C4) // "1 3 4" Complete enum type with strings [best practice]

Assuming you wish for invalid JSON payloads to fail, implement the Unmarshaler interface: https://play.golang.org/p/zuchzQ0vmo

Working with enums in Go, #programming | #golang. October 4, 2019. Working with enums in Go. Enums (​short of enumerators), identifiers that behave like constants, are useful parts of In the case of integer custom type, iota keyword can be used to simplify the definition. If an empty value is acceptable for enum, I validate the values during JSON  Go by Example: Constants and iota Go supports constants of character, string, boolean, and numeric values. We can use iota to simulate C’s enum or #define constant.

use go generate with github.com/alvaroloes/enumer

package main

import "fmt"

//go:generate enumer -type=StatusType
type StatusType int

const (
    PENDING StatusType = iota
    APPROVED
    REJECTED
)

func main() {
    fmt.Println(StatusType(0).IsAStatusType()) // true
    fmt.Println(StatusType(1).IsAStatusType()) // true
    fmt.Println(StatusType(2).IsAStatusType()) // true
    fmt.Println(StatusType(3).IsAStatusType()) // false
}

iota: Elegant Constants in Golang, Learn how to optimize your use of constants in Golang using iota. There are times when there's no inherently meaningful value for a thing. type Stereotype int const ( TypicalNoob Stereotype = iota // 0 TypicalHipster // 1  The left operand must either have an integer type or be an untyped constant that can represent a value of type int. The rule - If the left operand of a shift expression is an untyped constant, the result is an untyped integer constant; otherwise the result is of the same type as the left operand.

the iota is merely a compiler thing. The code is equivalent to:

const PENDING int = 0
const APPROVED int = 1
...

So to design a function CheckValid() to decide if the value is among the given values. You could either use user6169399's method if your const is in a continuous range. Or you could simply define a var map[YOUR_TYPE_HERE]bool to validate.

func (t YOUR_TYPE) CheckValid(){
    if _, ok:=map[t];ok return true
    else return false
}

Ultimate Visual Guide to Go Enums and iota, Golang Enums & iota Guide — Full of tips and tricks with visuals and runnable An enum groups related constants together in one type. Don't use iota for a list of predefined values like FTP server status codes. So, you can't know whether the Activity is initialized or not; Is it really in the Sleeping state? To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded. t, ok := i.(T) If i holds a T, then t will be the underlying value and ok will be true.

Golang Const, Var Examples: Iota, This is a constant value: we can use a const block for it. Golang program that uses iota in const package main import "fmt" const ( Low = 5 * iota main() { // Use a constant string in a func. const color = "Blue" // Test the constant. if color == "Blue" { fmt. Sometimes using a type on an integer constant will cause an error. You must assign a value at the time of the constant declaration, you can't assign a value later as with variables. package main import "fmt" const PRODUCT string = "Canada" const PRICE = 500 func main() { fmt.Println(PRODUCT) fmt.Println(PRICE) } You can also omit the type at the time the constant is declared. The type of the value assigned to

The Go Programming Language Specification, Index expressions: Slice expressions: Type assertions: Calls: Passing arguments to This is a reference manual for the Go programming language. A rune literal represents a rune constant, an integer value identifying a Unicode code point. The predeclared identifier iota denotes an integer constant. Any other value will be returning java.lang.IllegalArgumentException: No enum constant. With Go, it’s different. Most often you create a custom type (LeaveType) and define constants of that type. In the case of integer custom type, iota keyword can be used to simplify the definition.

src/go/constant/value.go - The Go Programming Language, 27 type Kind int 28 29 const ( 30 // unknown values 31 Unknown Kind = iota 32 33 Make sure that m*10 < 10 even after 209 // rounding up: m*10 + 0.5e-5 < 10​  In general, two values can only be compared if one value is of the same (or underlying) type with the other. There are, however, more nuances to this rule that are explored in the next section

Comments
  • Detail not related to your question, but constants should not be uppercased (C style). It is Pending/Approved/Rejected
  • Possible duplicate of Golang: Creating a Constant Type and Restricting the Type's Values
  • Making StatusType unexported and using an interface won't cut it. See a dirty trick which I presented in Golang: Creating a Constant Type and Restricting the Type's Values which allows to implement interfaces even with unexported methods. In fact, no constant type can be restricted this way.
  • @icza Agree (and upvoted). I thought about unexported wrapper struct, but I want to stay as close as possible to the original code of the OP. As I say in the answer, "caveat applies".