Go: A counter with methods

A counter is the smallest useful type with methods.

What to build

A program that drives a counter from commands.

Requirements

  • Define a Counter type with the methods Inc, Dec, Reset and Value; the first three change it.
  • Read n, then n commands: inc, dec, reset or print. The counter starts at 0.
  • For print output the current value.

Input

Line 1: n. Then n commands, one per word.

Output

One number for each print command.

Constraints

1 ≤ n ≤ 100.

Example

Input:

6
inc inc print dec print reset

Output:

2
1

Why it works

Inc, Dec and Reset have pointer receivers, so they change the counter in main. With a value receiver the counter would stay at 0.

Examples

Example 1 · Input
6
inc inc print dec print reset
Expected output
2
1
Example 2 · Input
3
print dec print
Expected output
0
-1

Hints

Hint 1

type Counter struct { value int } with pointer receiver methods Inc, Dec and Reset.

Hint 2

Write a method Value() int and print it for the print command.

Solution

Show one correct solution (try it yourself first)
package main

import "fmt"

type Counter struct {
	value int
}

func (c *Counter) Inc()   { c.value++ }
func (c *Counter) Dec()   { c.value-- }
func (c *Counter) Reset() { c.value = 0 }
func (c Counter) Value() int {
	return c.value
}

func main() {
	var n int
	fmt.Scan(&n)
	var c Counter
	for i := 0; i < n; i++ {
		var cmd string
		fmt.Scan(&cmd)
		switch cmd {
		case "inc":
			c.Inc()
		case "dec":
			c.Dec()
		case "reset":
			c.Reset()
		case "print":
			fmt.Println(c.Value())
		}
	}
}

▶ Open this solution in the compiler

Lesson: Methods and pointers →