[英]Golang equivalent to Python's NotImplementedException
当您定义一个带有您不想实现的方法的接口时,Golang 中是否有与在 Python 中引发NotImplementedException
的等价物? 这是惯用的 Golang 吗?
例如:
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
}
通常在 golang 中,如果你想实现错误处理,你会返回一个错误
type MyInterface interface {
Method1() bool
Method2() (bool, error)
}
然后你可以返回一个错误。 你也可以记录,或者像@coredump 在评论中所说的那样恐慌。
这是我在 Go 中实现 gRPC 生成的示例:
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")
}
或者,您可以在方法中记录一个错误,然后返回一个 nil 以满足方法契约。
一个空的 var 会做到这一点
var _ MyInterface = &Thing{}
如果Thing
没有实现接口MyInterface
,编译将失败
func someFunc() {
panic("someFunc not implemented")
}
这是 go 中的一种常见模式,如果失败,您将返回结果或错误。
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")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.