CodingNeed.

1 · Values and control flow · 25 MIN

Values, functions and explicit returns

A function signature describes what enters and leaves a computation.

Go infers a local variable’s type with :=, but function parameters and results have explicit types. Whole-number prices avoid introducing rounding into this first example. The total function receives copies of its integer arguments and returns a value without printing. Keeping computation separate from output lets the same function be called from a command-line program, an HTTP handler or a test. Start by predicting both printed results, then change only the arguments. Machine-sized int can overflow, so financial or untrusted inputs need an explicit range policy.

Separate arithmetic from fmt.Println so each can be tested independently.

Read the example

package main
import "fmt"
func total(price int, quantity int) int { return price * quantity }
func main() {
  price := 12
  fmt.Println(total(price, 3))
  fmt.Println(total(price, 0))
}
Check the expected output
36
0

Your challenge

Add a discount function that subtracts a whole-number amount without allowing a negative total.

Solution cost: O(1) arithmetic for fixed-width integers. time · O(1) auxiliary state. space

Common trap

Integer division truncates; converting a result afterwards cannot restore a discarded fraction.

Study the project implementation
package main
import "fmt"
func total(price int, quantity int) int { return price * quantity }
func main() {
  price := 12
  fmt.Println(total(price, 3))
  fmt.Println(total(price, 0))
}

Further reading: Official documentation

Next lesson: Loops, slices and shared storage

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.