Go Variables and Data Types
Variables store values. In Go, every variable has a type that cannot change.
Declaring Variables
Go has two ways to create a variable:
Example
package main
import "fmt"
func main() {
var city string = "Karachi"
var students = 40 // type is inferred as int
fee := 3500 // short declaration
fee = 3000
fmt.Println(city, students, fee)
}Karachi 40 3000
| Form | Where you can use it | Example |
|---|---|---|
var name type = value | Anywhere | var age int = 20 |
var name = value | Anywhere | var age = 20 |
name := value | Only inside functions | age := 20 |
:= creates a new variable. To change a variable that already exists, use plain =.
Zero Values
If you declare a variable without a value, Go gives it a zero value. There are no "empty" or random values in Go.
Example
package main
import "fmt"
func main() {
var count int
var price float64
var name string
var ready bool
fmt.Println(count, price, ready)
fmt.Printf("name is %q\n", name)
}0 0 false name is ""
Basic Data Types
| Type | Stores | Example | Zero value |
|---|---|---|---|
int | Whole numbers | 42 | 0 |
float64 | Decimal numbers | 99.5 | 0 |
string | Text | "Quetta" | "" |
bool | true or false | true | false |
rune | One character (Unicode) | 'A' | 0 |
byte | One small number (0 to 255) | 65 | 0 |
There are also sized versions such as int8, int64 and float32, but int and float64 are the usual choices.
Seeing a Type
The %T verb of Printf shows a value's type, and %v shows the value itself:
Example
package main
import "fmt"
func main() {
a := 10
b := 3.5
c := "hello"
d := true
fmt.Printf("%v is %T\n", a, a)
fmt.Printf("%v is %T\n", b, b)
fmt.Printf("%v is %T\n", c, c)
fmt.Printf("%v is %T\n", d, d)
}10 is int 3.5 is float64 hello is string true is bool
Multiple Variables
You can declare several variables on one line:
Example
x, y := 5, 8
var first, last string = "Ayesha", "Khan"Constants
A constant's value is fixed when the program is compiled. Use const:
Example
package main
import "fmt"
const Institute = "Workownix"
const Pi = 3.14159
func main() {
fmt.Println(Institute)
fmt.Println(Pi * 2)
}Workownix 6.28318
Type Conversion
Go never converts types for you. Write the type name like a function: float64(x), int(y). To turn text into numbers, use the strconv package.
Example
package main
import (
"fmt"
"strconv"
)
func main() {
marks := 45
total := 60
percent := float64(marks) / float64(total) * 100
fmt.Println(percent)
n, err := strconv.Atoi("123")
fmt.Println(n+1, err)
text := strconv.Itoa(2026)
fmt.Println("Year " + text)
}75 124 <nil> Year 2026
strconv.Atoi returns two values: the number and an error. <nil> means there was no error. You will learn more about errors in the functions lesson.
Exercise
Exercise
What is the value of x after var x int?
