Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to create a method of a structure in golang that is called automatically?
    text
    copied!<p>I have to create a something like a substitute of 2 levels of inheritance in golang, i.e., in a package, I have a structure(<strong>A</strong>), which is inherited(embedded as an anonymous field) by another structure(<strong>B</strong>) in another package, whose object is to be utilized by the "<strong>main</strong>" package.</p> <p>Now, I've created an initializer method for the "B" (<strong>BPlease</strong>) that returns an object of B (say,<strong>B_obj</strong>). I can call this initializer(<strong>BPlease</strong>) from my "main" package at the start of the program.</p> <p>One of the methods of "B" (say, <strong>HelloB()</strong>), calls a method of "A"(say,<strong>HelloA()</strong>) during execution, using "B's" object.</p> <p>But what I really want is, something like a constructor for "A" that can initialize its fields (preferably when B_obj was created in package "main") before "B" calls any methods of "A". </p> <p>How to achieve this? </p> <p>I tried creating an initializer(<strong>APlease</strong>) for "A" as well and called it (<strong>BPlease</strong>) to get an object of "A" (A_obj). But I found this object useless as I couldn't utilize it to call "A's" method (HelloA()) inside a method of "B" (HelloB()). It would be great if someone can tell me how to utilize this object (A_obj).</p> <p>Here's some code to clarify my query:</p> <pre><code> package A type A struct { whatever } func (A_obj *A) HelloA(){performs some operation...} // a method of A() func APlease() A { return A{initialize A fields} } ------------------------------------------------------------------------------- package B type B struct { A B fields } func BPlease() B { return B{ A_obj := APlease() // useless to me.... how to utilise this? initialize B fields} } func (B_obj *B) HelloB(){ // a method of B{} call B_obj.HelloA() // valid as A is an anon field in B struct some other operations // but A's fields are not initialized for B_obj ...} --------------------------------------------------- package main import "B" import "A" func main(){ B_obj := B.BPlease() // what I want is, calling this should initialize A's fields for B_obj as well so that when HelloB() calls B_obj.HelloA(), it utilises A's field that have been initialized. } </code></pre> <p>I cannot pass all field-values as parameters to B_obj as there are a lot of fields, and also, some field values are generated by calling a method of the same structure.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload