முக்கிய உள்ளடக்கத்திற்குச் செல்லவும்
eLearner.app
தொகுதி 2 · பாடம் 1 இன் 5பாடத்திட்டத்தில் 6/50~10 min
தொகுதி பாடங்கள் (1/5)

if, else, மற்றும் init அறிக்கைகள்

In Go the if syntax is the classic one but with two important differences compared to C/Java: no parentheses around the condition, and the ability to declare a temporary variable directly in the if (the init statement).

Basic syntax

Go
if temperatura > 30 {
    fmt.Println("caldo")
} else if temperatura > 20 {
    fmt.Println("mite")
} else {
    fmt.Println("fresco")
}

Braces are mandatory, even for single-line blocks. The condition must be of type bool: no "truthiness" like Python or JS.

Go
n := 0
// if n { ... }   // ERRORE: int non è bool
if n != 0 { ... }  // ok

Init statement: scope limited to the if

You can declare a variable valid only inside if/else, separating it from the condition with ;:

Go
if v, err := call(); err == nil {
    fmt.Println("ok", v)
} else {
    fmt.Println("ko", err)
}
// qui v ed err NON esistono più

It is the idiomatic pattern for handling errors without polluting the outer scope.

Shadowing in the if scope

If an outer variable gets "shadowed" by the init, inside the if the local version wins. Right after, the outer one re-emerges.

Go
x := 10
if x := 3; x > 5 {
    fmt.Println("dentro:", x)  // mai stampato (3 < 5)
} else {
    fmt.Println("else:", x)    // 3
}
fmt.Println("dopo:", x)         // 10 — quella esterna

No ternary operator

Go has no cond ? a : b. For conditional assignments you need an if/else in 3-4 lines — it is a design choice to favour readability.

Go
var label string
if age >= 18 {
    label = "adulto"
} else {
    label = "minore"
}

Try it

உடற்பயிற்சி#go.m2.l1.e1
முயற்சிகள்: 0ஏற்றுகிறது…

Print 'positivo', 'zero' or 'negativo' depending on the value of n.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

`if / else if / else` chain with conditions on the sign.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்

உடற்பயிற்சி#go.m2.l1.e2
முயற்சிகள்: 0ஏற்றுகிறது…

Use the init statement to declare v := 42 in the if and print it only if v >= 18.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

Syntax: `if init; condition { ... }`.

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்

Quiz#go.m2.l1.e3
தயார்

What does this program print?

Go
x := 10
if x := 3; x > 5 {
    fmt.Println("dentro:", x)
} else {
    fmt.Println("else:", x)
}
fmt.Println("dopo:", x)
பதில் விருப்பங்கள்

Recap

  • Conditions without parentheses, braces always mandatory.
  • The condition must be bool: no implicit truthiness.
  • Init if v, err := f(); err == nil { ... } limits the scope of v and err.
  • Shadowing in the init: be careful not to shadow outer variables.
  • No ternary: write an expanded if/else.