1
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??

2 Answers 2

1

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 .

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Thanks you @icza for the explanation. I learn something new today. But what type ScoreType int does do?
@aizen0002 type ScoreType int is a type definition: creates a new ScoreType type with int as its underlying type. See answer #1 and answer #2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.