0

我试图在 GO 中创建错误的子类型。我之前就这个问题问过一个问题。

现在我面临多种类型的问题。以下代码显示了错误类型定义:

/* Interfaces */
type UniversalError interface {
    CommonError1
}

type CommonError1 interface {
    error
    CommonError1()
}

/* Structs */
type Error1 struct {
    reason string
}

type Error2 struct {
    reason string
}

type Error3 struct {
    reason string
}

/* Interface function implementations */
func (error1 Error1) Error() string {
    return fmt.Sprintf(error1.reason)
}

func (error2 Error2) Error() string {
    return fmt.Sprintf(error2.reason)
}

func (error3 Error3) Error() string {
    return fmt.Sprintf(error3.reason)
}

func (Error1) CommonError1() {}
func (Error2) CommonError1() {}
func (Error3) UniversalError() {}

当我尝试运行以下代码时:

func main() {
    var err1 = Error1{reason: "Error reason 1"}
    var err2 = Error2{reason: "Error reason 2"}
    var err3 = Error3{reason: "Error reason 3"}

    fmt.Println("\n**** Types *****")
    printType(err1)
    printType(err2)
    printType(err3)
}

func printType(param error) {
    switch param.(type) {
    case UniversalError:
        switch param.(type) {
        case CommonError1:
            switch param.(type) {
            case Error1:
                fmt.Println("Error1 found")
            case Error2:
                fmt.Println("Error2 found")
            default:
                fmt.Println("CommonError1 found, but Does not belong to Error1 or Error2")
            }
        default:
            fmt.Println("Error3 Found")
        }
    default:
        fmt.Println("Error belongs to an unidentified type")
    }
}

printType()函数打印以下内容:

**** Types *****
Error1 found
Error2 found
CommonError1 found, but Does not belong to Error1 or Error2

我需要将 的类型Error3标识为UniversalError,而不是CommonError1. 我怎样才能做到这一点?我的方法有什么问题吗?

4

1 回答 1

1

您使用该UniversalError()方法,但您没有将其添加到接口“定义”中,因此请执行以下操作:

type UniversalError interface {
    CommonError1
    UniversalError()
}

而你想Error3成为一个UniversalError. 要Error3成为UniversalError,它必须实现其所有方法:UniversalError()CommonError1(). 所以你必须添加这两种方法:

func (Error3) CommonError1()   {}
func (Error3) UniversalError() {}

通过这些更改,输出将是(在Go Playground上尝试):

**** Types *****
Error belongs to an unidentified type
Error belongs to an unidentified type
CommonError1 found, but Does not belong to Error1 or Error2

提示:如果您希望编译时保证某个具体类型实现某个接口,请使用如下所示的空白变量声明:

var _ UniversalError = Error3{}

上面的声明将 的值赋给Error3类型为 的变量UniversalError。不应该Error3满足UniversalError,你会得到一个编译时错误。由于使用了空白标识符,上述声明不会引入新变量,这只是编译时检查。

如果您要删除该Error3.CommonError1()方法:

//func (Error3) CommonError1()   {}
func (Error3) UniversalError() {}

然后你会立即得到一个编译时错误:

./prog.go:49:5: cannot use Error3 literal (type Error3) as type UniversalError in assignment:
    Error3 does not implement UniversalError (missing CommonError1 method)
于 2019-06-13T13:25:03.503 回答