Search code examples
gorevelobject-composition

Make object accessible in inherited method in golang


I am trying to implement inheritence in golang. Below is example:

type A struct {
  Number int
}

type B struct{
  A
  name String
}

func (a A) GetNumber() {
    // Here I want to use instance of B
    fmt.Println(a) // but this is giving me instance of A
}

Is it possible to get instance of B in function of A if A is being inherited by B?


Solution

  • First of all, there is an error in your code. Until you have not created another type defined as String you have to correct it to string.

    Then in Go you can use composite structs, which means you can access a struct field included in another struct directly, as you already did.

    This means that you can invoke a method on a method receiver which does have the struct fields declared. To correct your example, if i'm understand correctly your question:

    package main
    
    import (
        "fmt"
    )
    
    type A struct {
        Number int
    }
    
    type B struct{
        A
        name string
    }
    
    func main() {
        b := &B{A{1}, "George"}
        b.GetValues()
    }
    
    func (b B) GetValues() {    
        fmt.Println(b.Number)
        fmt.Println(b.name)
    }
    

    In the example below because struct A is included in struct B this means you can invoke a struct field declared in struct A in the GetValues method. This is because struct B inherits the struct A fields.

    https://play.golang.org/p/B-XJc6jddE