Go course

Constants and FormattingConstants

Go

Display

Theme

Constants and Formatting · Test exercise

Constants

A constant is a value you set once and can't change while the program runs. You create one with the const keyword:

const namaToko = "Laundry Kilat"
const jamBuka = 8

Here's how that differs from a variable:

var stok = 10
stok = 12 // boleh, variabel bisa diubah

const maksimum = 100
maksimum = 200 // ERROR: cannot assign to maksimum

Reassigning the variable stok is fine; reassigning the constant maksimum is a compile error.

When should you use a constant?

Use constants for values that are guaranteed to stay the same: rates, limits, the app name, the number of seconds in a minute, and so on. Giving them a name makes your code much easier to read than "magic numbers" scattered all over the place:

// kurang jelas
total := berat*7000 + 2000

// lebih jelas
total := berat*hargaPerKg + biayaAdmin

The first version is less clear; the second tells you what each number means. And if the rate changes one day, you only have to update a single constant declaration.

The value must be known at compile time

The compiler has to be able to work out a constant's value before the program runs. Literals (7000, "halo", true) and arithmetic between constants are allowed:

const menitPerJam = 60
const detikPerJam = menitPerJam * 60 // boleh: dihitung saat kompilasi

You can declare constants at package level (outside any function) or inside a function.

Task

A pay-by-the-kilo laundry wants to calculate its washing fees.

  1. Change the values of the two package-level constants:
    • hargaPerKg (price per kg) set to 7000
    • biayaAdmin (admin fee) set to 2000
  2. Complete the function biayaLaundry(beratKg int) int so it returns beratKg * hargaPerKg + biayaAdmin.

Example: biayaLaundry(3) returns 23000.

The tests will make sure both are really constants, not variables.

main.go
package main

import "fmt"

// TODO: isi nilai konstanta sesuai tugas
const hargaPerKg = 0
const biayaAdmin = 0

func biayaLaundry(beratKg int) int {
	// TODO: kembalikan beratKg * hargaPerKg + biayaAdmin
	return 0
}

func main() {
	fmt.Println("Biaya laundry 3 kg:", biayaLaundry(3))
}

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)