簡體   English   中英

Golang 等價於 Python 的 NotImplementedException

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM