0

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?

Paritosh Singh
  • 6,288
  • 5
  • 37
  • 56
  • 2
    There is no inheritance in Go. Some related / possible duplicates: [one](http://stackoverflow.com/questions/21251242/is-it-possible-to-call-overridden-method-from-parent-struct-in-golang), [two](http://stackoverflow.com/questions/30622605/can-embedded-struct-method-have-knowledge-of-parent-child), [three](http://stackoverflow.com/questions/29390736/go-embedded-struct-call-child-method-instead-parent-method), [four](http://stackoverflow.com/questions/29144622/what-is-the-idiomatic-way-in-go-to-create-a-complex-hierarchy-of-structs). – icza May 13 '16 at 08:00

1 Answers1

2

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

Endre Simo
  • 11,330
  • 2
  • 40
  • 49
  • This answer is irrelevant to the question, as it asked how to get values from B in methods defined on A. – opErAtiA Aug 01 '22 at 23:40