Here I am again for the 30 Days of Code in Go. This is Saturday, but that doesn’t mean I will not code =). First of all, before starting to code I was thinking about the theme: classes. I was wondering if Go had support for it and I found some interesting material to read. First I read Why Go’s structs are superior to class-based inheritance and I found out the the inheritance model of Go is different from that of Java. Basically, you do not actually specify which class implements an interface, but the compiler. A class can implement several interfaces, not being limited to one super-class like in Java or C++. Another materials I read were Go by Example Structs, methods and interfaces. I am not so well versed on the syntax, but it is not hard to grasp it and start coding. Nevertheless, HackerRank was good to me and gave some starter code and I just implemented the methods.

The goal of this task is to receive an input $T$ indicating the number of ages of people that will be given later. For each of these ages, we have an instance that has a method that can say if the person is young, a teenager or old. It also checks for invalid ages and can increment the age by another method. The full solution is given below.

package main

import "fmt"

type person struct {
 age int

func (p person) NewPerson(initialAge int) person {
 if initialAge < 0 {
  fmt.Printf("Age is not valid, setting age to 0.\n")
  p.age = 0
 } else {
  p.age = initialAge

 return p

func (p person) amIOld() {
 if p.age < 13 {
  fmt.Printf("You are young.\n")
 } else if p.age >= 13 && p.age < 18 {
  fmt.Printf("You are a teenager.\n")
 } else {
  fmt.Printf("You are old.\n")

func (p person) yearPasses() person {
 return p

func main() {
 var T, age int
 // get number of persons that
 // will be given
 for i := 0; i < T; i++ {
  p := person{age: age}
  // constructor? kind of
  p = p.NewPerson(age)
  for j := 0; j < 3; j++ {
   p = p.yearPasses()

Executing it:

$ ./day_04
1 #T
15 #age
# output below
You are a teenager.
# the next considers some years have passed
You are old.

That’s all for this day of coding in Go! Thanks for reading!