variables and declaration Flashcards
(8 cards)
Variable Declaration (Explicit)
var name string = “Alice”
var age int = 25
Explanation:
var keyword declares a variable.
Explicitly specifies type (string, int, etc.).
Can be used inside and outside functions.
Short Variable Declaration (Inferred Type)
name := “Bob” // string
age := 30 // int
Explanation:
:= infers the type automatically.
Only works inside functions.
Preferred for concise code.
Zero Values (Default Values)
var a int // 0
var b string // “”
var c bool // false
Explanation:
Uninitialized variables get default zero values.
int: 0, string: “”, bool: false.
Multiple Variable Declaration
var x, y int = 10, 20
a, b := “hello”, true
Explanation:
Declares multiple variables in one line
Works with both var and :=
Type Conversion
i := 42
f := float64(i) // Convert int to float64
Explanation:
Go requires explicit type conversion.
Syntax: Type(value).
Constants (Immutable Values)
const Pi = 3.14
const Greeting = “Hello”
Explanation:
const declares unchangeable values.
Must be initialized at declaration.
Variable Scope
package main
var globalVar = “I’m global!”
func main() {
localVar := “I’m local!”
}
Explanation:
Global: Declared outside functions (accessible everywhere in the package).
Local: Declared inside functions (accessible only within that function).
Blank Identifier (_)
_, err := someFunction() // Ignore the first return value
Explanation:
_ discards unwanted values (avoids compiler errors).