Interface with fields

Is there any hack for interfaces to have fields?
The interface with function definition is good for most of the time.

Is there any chance?
Why go has decided to keep interfaces only with functions?

Hi @Mahesh_Kumar1, welcome to the forum.

The purpose of interfaces is to declare a set of functions. Interfaces serve for describing behavior, and not for storing state.

If you want to have fields, you can use structs.

What use case do you have where you think you cannot use structs?

I understand the idea.
I was thinking something else which confused me.

I was thinking…
I am sending some states to the web. I have an interface with some behaviour. The struct is only implementing the behaviour. It has some fields.

I was thinking to force the struct to keep the minimum required fields as defined in the interface.

@christophberger

In my main func, i have handlers. Say, adminhandler, userhandler and few more.

Every handler must use *template.Template variable

How do i force all the handlers satisfy this condition?

In future, they must satisfy by using logger, db and more.

I can alternatively use middleware.
Is this a good reason to have fields in interface?

I begin to halfway understand the problem, but I still have no clear picture.

Can you share some minimal example code to show how the handers use *template.Template?

And a more philosophical question: Does the condition have to be baked into code? Or would it be sufficient to communicate the condition in the documentation, as a convention?

(Similar to Go’s error handling, which is also a convention and not enforced by the compiler.)

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