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

பூஜ்ஜிய மதிப்பு மற்றும் வகை மாற்றங்கள்

In Go every variable declared without an explicit value receives a zero value: the "neutral value" of its type. It's a huge difference from JavaScript, where let x; produces undefined, or C, where you end up with garbage memory. No undefined, no UB: just zero.

The zero value table

CategoryTypeZero value
Numericint, int64, float32, float64, uint, ...0
Booleanboolfalse
Stringstring"" (empty string)
Pointer*Tnil
Slice / Map / Channel[]T, map[K]V, chan Tnil
Function / Interfacefunc(...), interface{...}nil
StructT struct{...}all fields at their zero value
Go
var i int        // 0
var f float64    // 0
var s string     // ""
var b bool       // false
var p *int       // nil
var nums []int   // nil  (NB: una slice nil ha len 0 e si può iterare!)

Conversions are ALWAYS explicit

Unlike C, Python or JS, Go does not automatically promote one numeric type to another: you must write type(value).

Go
i := 42
var f float64 = float64(i)
var u uint = uint(i)

This is true even for "compatible" types like int and int64: an explicit conversion is always required.

Go
var a int = 10
var b int64 = int64(a)  // obbligatorio

Conversion between numerics: watch out for truncation

Going from float64 to int truncates towards zero, it does not round:

Go
f := 3.9
i := int(f)   // 3, non 4
n := int(-3.9) // -3, non -4

String ↔ number conversion

string(65) does NOT give "65": it gives "A" (the rune with code point 65). For string → number and vice versa you need the strconv package:

Go
import "strconv"

s := strconv.Itoa(42)        // "42"
n, err := strconv.Atoi("42") // 42, nil

We'll cover it in depth in the Stdlib module.

Your turn

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

Declare a variable counter of type int without initializing it and print it. Expected: 0.

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

Without an initializer the variable takes the zero value of the type.

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

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

Given the integer n=10, convert n to float64 and divide by 4. Print the result (expected 2.5).

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

Without the explicit conversion, `n / 4` is an integer division that gives 2.

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

Quiz#go.m1.l2.e3
தயார்

What does this code print?

Go
f := 3.7
fmt.Println(int(f))
பதில் விருப்பங்கள்

Recap

  • Every type has a consistent zero value: no undefined, no UB.
  • Slice/map/chan/func/interface/pointer have zero value nil.
  • Numeric conversions are always explicit with type(value).
  • int(float) truncates towards zero; to round use math.Round.
  • For string ↔ number use the strconv package (NOT a direct cast).