Constructor in golang

In C, following syntax is used before a function name to execute it before main or when a library is loaded
attribute((constructor))

What is the syntax in golang?
Go binary contains init function which is called before main. But init function does not called for go plugin or shared go library. Is there any other function/event (of plugin/shared go library) which is called when a plugin/library is loaded?

Go has no constructors. Values are initialized with their zero value. If the zero value is insufficient, then convention is to a name a function that creates a T as NewT.

3 Likes

What about the init function in goplugin/shared-go-library? Is there any function in goplugin/shared-go-library which is called during load?

if you would use init() then you should put each class to own package.

but:

  • each constructor/init() would be runt before main()
  • even go-core team tells init was a mistake and it should not be used.

I made a mistake of trying to implement functionality from other OO languages, that was mistake.
I should have just tried to unlearn old consepts and write the same look and feel as other go code… would have saved me a lot of time and architechtural mistakes.

What about the init function in goplugin/shared-go-library? Is there any function in goplugin/shared-go-library which is called during load?

Shared library init functions will be called if you import them. See this question on SO for more details. Can you maybe post some actual problematic code or distill the problem you are specifically trying to solve?

even go-core team tells init was a mistake and it should not be used.

@apmattil could you elaborate? I don’t know of any guidelines from the core team that recommend not using init. See also this proposal to remove init and its’ reception by the core team.

my mistake about init() still favored … sorry about miss information.
I also did not realize your use case was about plugin’s, I quess the question is already answered at the stackoverflow.

Didn’t mean to sound combative in any way btw! I was just genuinely curious. Also in that issue they do say that init might be over-used and documentation should cover specific use cases where it’s idiomatic to use it. :slight_smile:

Created a plugin (testplug.so). Created a go application and used plugin (plugin.open). testplug.so is different code. When this plugin is loaded, is there any method which tells that the plugin has been loaded? If I want to initialize some variables before calling any function of plugin then I can do that when plugin has been loaded.

plugin has a disadvantage that it can’t be used across different go versions/sub versions.
Shared library can be used in that case. I created a shared library using “go install”. When shared library is successfully loaded is there any method which is called?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.