Skip to content

Proposal: Add a generic-based compile-time interface assertion helper #742

@nickxudotme

Description

@nickxudotme

TL;DR

Introduce a modern, generic-friendly alternative to Go's traditional interface implementation check.

Current idiom:

var _ SomeInterface = (*SomeStruct)(nil)

Proposed alternative:

var _ = lo.Implement[SomeInterface](&SomeStruct{})

Both provide a compile-time assertion, but the new form aims to be more explicit and idiomatic in the era of generics.


Motivation

Many long-standing Go idioms have gradually been replaced by more modern, expressive forms as the language evolves.

For example, deleting a slice range used to require manual slicing:

a = append(a[:i], a[j:]...)

Now Go encourages a clearer and safer built-in helper:

a = slices.Delete(a, i, j)

However, one particular idiom still carries the “old Go” flavor—the pattern for asserting that a struct implements an interface:

var _ SomeInterface = (*SomeStruct)(nil)

Although widely used, this pattern has some drawbacks:

  • It is not immediately intuitive for newcomers.
  • It reads more like a trick than an explicit assertion.
  • It feels out of place in modern, generic-heavy Go codebases.

Since lo embraces functional-style utilities and code clarity, this proposal explores whether a small generic helper could provide a more expressive alternative.


Proposal

Introduce a generic helper that performs a compile-time interface implementation check:

func Implement[T any](_ T) struct{} {
    return struct{}{}
}

Usage:

var _ = Implement[SomeInterface](&SomeStruct{})

Variants

Support asserting multiple implementations at once:

func Implement[T any](_ ...T) struct{} {
    return struct{}{}
}

var _ = Implement[SomeInterface](&SomeStruct{}, &AnotherStruct{})

Or a void-return version:

func Implement[T any](_ T) {}

func init() {
    Implement[SomeInterface](&SomeStruct{})
}

Why this might fit lo

  • It is tiny and almost zero-cost.
  • It improves clarity and self-documentation.
  • It complements lo’s philosophy of composable helpers.

Why it might not fit lo

  • lo traditionally focuses on functional utilities, not language-level contracts.
  • The classic idiom is already short and widely understood.
  • The community has not yet standardized a generic-based interface assertion pattern.

Alternative: publish under a smaller module

I understand this proposal is somewhat outside lo’s core domain, but if there’s interest, it could live in a small side package, such as:

  • lo/asserts
  • lo/constraints

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions