Go course

VariablesDeclaring Variables

Go

Display

Theme

Variables · Output exercise

Declaring Variables

You declare a variable with the var keyword, followed by its name and then its type:

var umur int
var nama string
var aktif bool

A variable declared without a value automatically holds the zero value for its type:

TypeZero value
int0
float640
string"" (empty string)
boolfalse

You can also give it a value right away:

var kota string = "Bandung"

Go doesn't allow local variables that are declared but never used — the program won't compile.

Task

A coffee shop queue app stores customer data. Declare three variables with var:

  • pelanggan ("customer") of type string, holding "Sari"
  • jumlahPesanan ("order count") of type int, holding 3
  • member of type bool, holding true

The printing code is already there. Expected output:

Pelanggan: Sari
Jumlah pesanan: 3
Member: true
main.go
package main

import "fmt"

func main() {
	// TODO: deklarasikan variabel pelanggan, jumlahPesanan, dan member
	var pelanggan string
	var jumlahPesanan int
	var member bool

	fmt.Println("Pelanggan:", pelanggan)
	fmt.Println("Jumlah pesanan:", jumlahPesanan)
	fmt.Println("Member:", member)
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)