Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Interface methods return itself or another interface #91

Closed
drumsta opened this issue Apr 4, 2024 · 1 comment
Closed

Interface methods return itself or another interface #91

drumsta opened this issue Apr 4, 2024 · 1 comment

Comments

@drumsta
Copy link

drumsta commented Apr 4, 2024

How to deal with the case below?

// Bad.
type Doer interface { Do() Doer }
type IDoer struct{}
func New() Doer { return new(IDoer)}
func (d *IDoer) Do() Doer {/*...*/ return d }

// Good.
type Doer interface { Do() Doer }
type IDoer struct{}
func New() *IDoer { return new(IDoer)}
func (d *IDoer) Do() *IDoer {/*...*/ return d}

// Very Good (Verify Interface Compliance in compile time)
var _ Doer = (*IDoer)(nil)

The above won't compile because of the error:

cannot use (*IDoer)(nil) (value of type *IDoer) as Doer value in variable declaration: *IDoer does not implement Doer (wrong type for method Do)
		have Do() *IDoer
		want Do() Doer

This use case is quite common designing libraries. As an example, standard slog package has this interface, that's Handler methods return the Handler interface.

type Handler interface {
	Enabled(context.Context, Level) bool
	WithAttrs(attrs []Attr) Handler
	WithGroup(name string) Handler
}
@butuzov
Copy link
Owner

butuzov commented Apr 13, 2024

closed as duplicate of #21

@butuzov butuzov closed this as completed Apr 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants