Go course

VariablesShort Variable Declaration :=

Go

Display

Theme

Variables · Test exercise

Short Variable Declaration :=

Inside a function, the most common way to create a variable is the short declaration with the := operator. Go figures out the type (type inference) from the value on the right:

nama := "Budi"     // string
skor := 90         // int
rasio := 0.75      // float64
lulus := true      // bool

You can create several variables at once:

lebar, tinggi := 1920, 1080

:= only works inside a function. Outside a function (at package level) you have to use var.

A quick word on functions

This exercise uses a function — we'll dig into them in Chapter 4. For now, all you need to know is that return sends a value back from the function.

Task

Complete the function luasPersegiPanjang(panjang, lebar int) int (rectangle area from length and width).

  1. Create a variable luas ("area") with := that holds panjang * lebar.
  2. Return luas.

Click Submit — the hidden tests will call your function with a few different values.

main.go
package main

import "fmt"

func luasPersegiPanjang(panjang, lebar int) int {
	// TODO: buat variabel luas dengan := lalu kembalikan
	return 0
}

func main() {
	fmt.Println("Luas 4x5 =", luasPersegiPanjang(4, 5))
}

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)