Golang equivalent to Python's NotImplementedException

8.8k Views Asked by At

Is there an equivalent in Golang to raising a NotImplementedException in Python when you define an interface with methods that you don't want to implement yet? Is this idiomatic Golang?

For example:

type MyInterface interface {
    Method1() bool
    Method2() bool
}


// Implement this interface
type Thing struct {}
func (t *Thing) Method1() bool {
    return true
}

func (t *Thing) Method2() bool {
    // I don't want to implement this yet
}
6

There are 6 best solutions below

0
On

Usually in golang if you want to implement error handling you return an error

type MyInterface interface {
    Method1() bool
    Method2() (bool, error)
}

Then you can return an error. You can also log, or panic as @coredump said in the comments.

0
On

a empty var will do this

var _ MyInterface = &Thing{}

if Thing doesn't implement the interface MyInterface, compile will fail

2
On
func someFunc() {
   panic("someFunc not implemented")
}
1
On

It's a common pattern in go, that you return your result or error in case of failure.

import (
    "errors"
    "fmt"
)

func (t *Thing) Method2() (bool, error) {
    // I don't want to implement this yet
   return nil, errors.New("Not implemented")
   // Also return fmt.Errorf("Not implemented")
}

func (t *Thing) Method3() (bool, error) {    
   return nil, fmt.Errorf("Not implemented")
}
0
On

If the method must not be called (yet?) because it is not (yet?) implemented, panicing is just the right thing to do (fail early).

func (t *Thing) Method2() bool {
    panic("Not implemented")
}

You could go further and use a true error:

func (t *Thing) Method2() bool {
    panic(errors.New("Not implemented"))
}

But I don't think this is necessary because this failure is not supposed to be caught (recovered) at runtime. Instead it exists just to tell the developer (s)he should use something else, so (s)he should have seen that message during early testing and fixed it.

Note that Go 1.21 has added errors.ErrUnsupported which you could also use:

func (t *Thing) Method2() bool {
    panic(errors.ErrUnsupported)
}
0
On

Here's an example that was generated from my implementation of gRPC in Go:

import (
    status "google.golang.org/grpc/status"
)

// . . .

// UnimplementedInstanceControlServer can be embedded to have forward compatible implementations.
type UnimplementedInstanceControlServer struct {
}

func (*UnimplementedInstanceControlServer) HealthCheck(ctx context.Context, req *empty.Empty) (*HealthCheckResult, error) {
    return nil, status.Errorf(codes.Unimplemented, "method HealthCheck not implemented")
}

Alternatively, you could log an error inside the method and then return a nil to satisfy the method contract.