Design a class in Golang

in #interview6 years ago (edited)


Today I have read this blog - http://tango-ruby.hatenablog.com/entry/2016/12/01/140840 and it introduces an interesting interview question.


In as few lines of code as possible, implement a class Person so that each instance of this class can have children and grandchildren (of that same class Person) - but not beyond grandchildren.


It is a simple question and asked to write in Ruby. But I wondered that how I will implement it in Golang and explain it in Golang. Golang does not have Class, but similar concept exists.


So, here is the Golang code I jotted.


```

package main


import "fmt"


type Children []Person


type Person struct {

name     string

children Children

}


// gland_children returns names of gland children.

func (p *Person) grand_children() []string {

var gland_children []string

for _, v := range p.children {

for _, vv := range v.children {

gland_children = append(gland_children, vv.name)

}

}

return gland_children

}


func main() {

gland_child1 := Person{"gland_child_1", nil}

gland_child2 := Person{"gland_child_2", nil}

child := Person{"child_1", []Person{gland_child1, gland_child2}}

parent := Person{"parent_1", []Person{child}}


fmt.Printf("parent        : %v \n", parent.name)

fmt.Printf("gland_children: %v \n", parent.grand_children())

}

```


Although Golang does not have Class, but has Struct. I guess that following questions were asked during writing the codes.


Q. What is `methods`?

A. Method is a function with a receiver which is an argument.


Q. Why receiver is used as a pointer?

A. There are two reasons. The first is that the methdod can modify the value that its receiver points to. The second is to avoid copying the value on each moethod call. - Ref: https://tour.golang.org/methods/8