Go Tutorial menu

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

go
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)
}
Output
Karachi 40 3000
FormWhere you can use itExample
var name type = valueAnywherevar age int = 20
var name = valueAnywherevar age = 20
name := valueOnly inside functionsage := 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

go
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)
}
Output
0 0 false
name is ""

Basic Data Types

TypeStoresExampleZero value
intWhole numbers420
float64Decimal numbers99.50
stringText"Quetta"""
booltrue or falsetruefalse
runeOne character (Unicode)'A'0
byteOne small number (0 to 255)650

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

go
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)
}
Output
10 is int
3.5 is float64
hello is string
true is bool

Multiple Variables

You can declare several variables on one line:

Example

go
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

go
package main

import "fmt"

const Institute = "Workownix"
const Pi = 3.14159

func main() {
	fmt.Println(Institute)
	fmt.Println(Pi * 2)
}
Output
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

go
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)
}
Output
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?

Learn Go with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp