0

im converting some code from python to go

here i want write equal code in go lang:

python :

while g_day_no >= g_days_in_month[i] + (i == 1 and leap):
    g_day_no -= g_days_in_month[i] + (i == 1 and leap)
    i+=1

my try:

leap := int32(1)
var i = int32(0)
for g_day_no >= (g_days_in_month[i] + (i == 1 && leap)){
    g_day_no -= g_days_in_month[i] + (i == 1 && leap)
    i+=1
}

but i have error in ide that say :

Invalid operation: i == 1 && leap (mismatched types bool and int32)

for this section (i == 1 && leap)

how can i correct this part of my code?

moh
  • 433
  • 10
  • 33

1 Answers1

1

Go is more strict about conditions. It requires booleans. leap is an integer, so just check the value:

g_day_no >= (g_days_in_month[i] || (i == 1 && leap!=0))

More detailed answer

Booleans (True and False) in Python correspond to the following integer values:

True=>1 False=>0

This can be seen with the following:

>>> True+0
1
>>> False+0
0

Therefore, when you have two booleans that are being added together, its the same as an OR:

True  + True  => 2 (True)
False + True  => 1 (True)
True  + False => 1 (True)
False + False => 0 (False)

This is the same "truth table" as OR:

True OR True => True False OR TRUE => True True OR False => True FALSE OR FALSE => False

Therefore, change your + to an || (|| is OR in Go).

poy
  • 10,063
  • 9
  • 49
  • 74
  • 1
    g_day_no >= g_days_in_month[i] + (i == 1 && leap != 0) still give me the error ``` Invalid operation: g_days_in_month[i] + (i == 1 && leap != 0) (mismatched types int32 and bool) ``` – moh Dec 17 '18 at 18:47
  • 1
    what about g_day_no -= g_days_in_month[i] + (i == 1 && leap) in inside of loop i did same thing but that dont work there i did this : g_day_no -= g_days_in_month[i] || (i == 1 && leap != 0) – moh Dec 17 '18 at 19:12
  • 1
    You will have to take the conditional and move that to an if statement. If the condition is true, subtract 1 from `g_day_no`. – poy Dec 17 '18 at 20:10