Skip to content

Variable Declaration & Assignment

Variables are used to store data in Harneet. Harneet provides flexible ways to declare and assign values to variables.

Explicit Type Declaration

You can explicitly declare the type of a variable when you declare it.

Explicit Type Declaration
1
2
3
package main
var x int = 42
var name string = "Hello"

Type Inference

Harneet can infer the type of a variable based on the value assigned to it.

Type Inference
1
2
3
package main
var x = 42        // x is inferred as int
var name = "Hello"  // name is inferred as string

Shorthand with Type Inference

Use var with an initializer to infer the type. This is the recommended shorthand for declaration + assignment.

Type Inference Shorthand
var x = 42          // inferred int
var message = "Hi there" // inferred string

Assignment

You can assign a new value to an existing variable using the = operator.

Variable Assignment
1
2
3
package main
var count = 10
count = 20 // Assign a new value

Zero Value Initialization

When a variable is declared without an explicit initial value, it is automatically initialized to its "zero value".

  • Integer Types: 0
  • Float Types: 0.0
  • String Type: "" (empty string)
  • Boolean Type: false
Zero Values
1
2
3
4
5
package main
var intVal int       // intVal is 0
var floatVal float64 // floatVal is 0.0
var strVal string    // strVal is ""
var boolVal bool     // boolVal is false

Multiple Assignment

Harneet supports assigning multiple values to multiple variables in a single statement. This is particularly useful for functions that return multiple values.

Function Returns

Function Return Values
package main
import math, fmt

function getAbs(num int) (int, string) {
    if num < 0 {
        return -num, ""
    }
    return num, ""
}

var result, err = getAbs(-42)
if err != "" {
    fmt.Println("Error:", err)
} else {
    fmt.Println("Absolute value:", result) // Output: Absolute value: 42
}

Multiple Expressions

Multiple Variable Declaration
1
2
3
package main
var name string, age int, score float64 = "Alice", 25, 98.5
var x, y, z int = 10, 20, 30

Multiple Assignment (single line)

Multiple Assignment (Single Line)
var a string, b int, c bool = "hello", 123, true

Blank Identifier

The blank identifier _ can be used to discard unwanted values in multiple assignment operations.

Blank Identifier
1
2
3
4
package main
import math

var value, _ = math.Max(10, 5) // Discard the error return value