Skip to content

proposal: cmd/compile: optimization for single-method interfaces #74456

Closed
@clipperhouse

Description

@clipperhouse

Proposal Details

It occurs to me that interfaces with single methods are ~isomorphic with passing funcs. Where one can pass a single-method interface, one can equivalently pass just that func.

My suggestion is that the complier might rewrite the call sites to pass this func instead of the interface, and avoid dynamic dispatch at runtime. I am curious if this idea is ~correct and whether it might be desirable.

type interface Fooer {
    Foo() Bar
}

func doSomethingWithFooer(fooer Fooer) {
    bar := fooer.Foo()
}

// becomes...

func doSomethingWithFooer(foo func() Bar) {
    bar := foo()
}

Exceptions

If one reflects or type-asserts against the interface, then substituting the func would not work. In that case, perhaps the rewrite would be to add the func as an argument, while also accepting the interface for reflection or type assertion.

// do both
func doSomethingWithFooer(fooer Fooer, foo func() Bar) {
    bar := foo()
    if fooer.(concreteThing)...
}

Thanks. Some related thinking here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    LanguageProposalIssues describing a requested change to the Go language specification.Proposal

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions