go compile_error ai_generated true

cannot embed non-interface type T

ID: go/cannot-embed-non-interface

Also available as: JSON · Markdown
92%Fix Rate
90%Confidence
50Evidence
2020-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
122 active

Root Cause

Attempting to embed a concrete type where only interfaces are allowed, or embedding a type that conflicts with another embedded type's methods. Go's embedding rules require careful type composition.

generic

Workarounds

  1. 95% success Use a named field instead of embedding
    // Instead of embedding:
    type MyStruct struct {
        SomeConcreteType  // ERROR: cannot embed
    }
    // Use a named field:
    type MyStruct struct {
        Inner SomeConcreteType
    }
    // Access: s.Inner.Method()

    Sources: https://go.dev/ref/spec#Struct_types

  2. 88% success Extract an interface from the concrete type and embed that
    type Doer interface {
        Do() error
    }
    type MyStruct struct {
        Doer  // embed the interface
    }
    // Then assign: s := MyStruct{Doer: concreteInstance}

    Sources: https://go.dev/doc/effective_go#embedding

Dead Ends

Common approaches that don't work:

  1. Using type assertion to cast the embedded type 95% fail

    The error is a compile-time error about type embedding rules, not a runtime type mismatch. Type assertions don't apply here.

  2. Creating a wrapper interface just to embed the type 65% fail

    If you need the concrete type's fields (not just methods), an interface won't help since interfaces only carry method sets.

Error Chain

Frequently confused with: