简体   繁体   中英

Golang equivalent to Python's NotImplementedException

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
}

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.

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.

a empty var will do this

var _ MyInterface = &Thing{}

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

func someFunc() {
   panic("someFunc not implemented")
}

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")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM