Home > Mobile >  golang syntax not able to understand defining variable using type
golang syntax not able to understand defining variable using type

Time:09-10

type ScoreType int
const (
    Food     ScoreType = iota
    Beverage 
    Water
    Cheese
)

Can any one tell what does it signify while using in struct?

We can directly use

var Kij int = 0

const (
    Food  int = Kij
    Beverage 
    Water
    Cheese
)

Are above are same or different??

CodePudding user response:

The first one compiles, the second is a compile-time error, so they can't possibly be the same. You can't use a variable to initialize a constant!

The first one will assign ScoreType(0) to Food, ScoreType(1) to Beverage etc. The value of iota is incremented on each line. Quoting from Spec: Iota:

Within a constant declaration, the predeclared identifier iota represents successive untyped integer constants. Its value is the index of the respective ConstSpec in that constant declaration, starting at zero.

To test it:

fmt.Println(Food)
fmt.Println(Beverage)
fmt.Println(Water)
fmt.Println(Cheese)

Which outputs (try it on the Go Playground):

0
1
2
3

In the second example if you'd use const Kij int = 0 instead of var, it would compile, but would assign 0 to all constants: Kij is not incremented on each line. The above print statements will output (try it on the Go Playground):

0
0
0
0

CodePudding user response:

Yes! they are different .

  1. the first one get compiled but second one raises error : (variable of type int) is not constant.

you can use the first example without declaring a new type ScoreType . but it's a best practice and increases your code readability .

based on your question it seems you don't have enough understanding about iota [ which is totally fine ] .I don't think it's a good idea to explain it here because there are a lot of great explanation on the internet :

https://yourbasic.org/golang/iota/ and https://yourbasic.org/golang/bitmask-flag-set-clear/

these two links will help you grasp the idea behind iota and the power it gives you . good luck with them .

  • Related