Saturday, May 5, 2012

GOLANG: Call inherited constructor

Golang is new and innovative program language from Google. It is fast enough, flexible and powerful. But if you want to program something classic OOP, it is not so easy. At least, you have to change your mind, turn at 180°.
So, here is my 1 hour research about classes in Golang and class constructors.

First, I already knew there is a kind of inheritance in Golang structs (or classes in traditional OOP language). Now I will check is there constructor chaining when creating new class. To be more clear, lets look at C# example:

public class ClassA {
  public int A;
  public int B;
  public ClassA() {
    A = 1;
    B = 2;
  }
}

public ClassB : ClassA {
  public string C;
  public ClassB() : base() {
    C = "test"
  }
}

So, after ClassB creation, all members are initialized.
How this can be done in Golang? The answer is: easy, but not so obviously. Let see  the Golang code (more customized and decorated with lots of println)

package main

type ClassA struct {
    A int
    B int
}

func (self *ClassA) PrintA() {
    println("A is ",self.A)
}

func NewClassA() *ClassA {
    a := &ClassA{1,2}
    println(a.A, a.B)
    return a
}

type ClassB struct {
    *ClassA
    C string
}

func NewClassB() *ClassB {
    b := &ClassB{}
    b.ClassA = NewClassA()
    println(b.A, b.B, b.C)
    return b
}

func NewClassB1() *ClassB {
    b := &ClassB{NewClassA(), "test"}
    return b
}


func main() {
    a := NewClassA()
    println("done A, a.A=",a.A,"a.B=",a.B,"\n")

    b := NewClassB()
    println(b.A, b.B, b.C)
    b.PrintA()
    println("\n")

    c := NewClassB1()
    println(c.C)   
}

results here:
1 2
done A, a.A= 1 a.B= 2

1 2
1 2
1 2
A is  1


1 2
test

So, calling (chaining) inherited constructor is easy, just place it at struct initialization like this:

 a =  ClassA{inheritded_constructor, ....}

or call it separately on parent member like this:

   this_class.parent = constructor()

Thats all. Hope this example will be useful.

PS: archlinux users can install golang with:
# pacman -Sy go

No comments:

Post a Comment