Parameters and Return Values
A function is a named piece of code you can call over and over. Here's the general shape:
func namaFungsi(parameter1 tipe1, parameter2 tipe2) tipeKembalian {
// isi fungsi
return nilai
}
That's the function name, its parameters with their types, the return type, and the function body.
Example:
func luasSegitiga(alas float64, tinggi float64) float64 {
return alas * tinggi / 2
}
func main() {
l := luasSegitiga(10, 4)
fmt.Println(l) // 20
}
Notice that in Go the type comes after the name, for parameters and variables alike.
Shortening parameter types
When several parameters in a row share the same type, you only need to write the type once, at the end:
func luasSegitiga(alas, tinggi float64) float64 {
return alas * tinggi / 2
}
Functions with no return value
If a function doesn't return anything, you just leave out the return type:
func sapa(nama string) {
fmt.Println("Halo,", nama)
}
Arguments are copied
Go passes arguments by value: the function gets a copy. Changing a parameter inside the function doesn't change the caller's variable.
func tambahSatu(x int) {
x = x + 1
}
n := 5
tambahSatu(n)
fmt.Println(n) // tetap 5
n is still 5 after the call.
Task
The online store "Rak Buku" calculates the final price of an order. Complete the function:
func hargaAkhir(harga, jumlah, diskonPersen int) int
The formula: subtotal = harga * jumlah (price times quantity), then take off a discount of diskonPersen percent. Use integer arithmetic in this order: subtotal * (100 - diskonPersen) / 100.
Example: hargaAkhir(50000, 3, 10) → 135000.