如何使用接口统一两个不同的结构?

tsg*_*tsg 2 struct interface go go-interface

我有以下代码:

package main

import (
    "log"
)

type Data struct {
    Id int
    Name string
}

type DataError struct {
    Message string
    ErrorCode string
}

func main() {
    response := Data{Id: 100, Name: `Name`}
    if true {
        response = DataError{Message: `message`, ErrorCode: `code`}
    }
    log.Println(response)
}
Run Code Online (Sandbox Code Playgroud)

此代码返回一个错误:

./start.go:20: 不能使用 DataError 文字(类型 DataError)作为赋值中的类型数据

似乎我无法分配给response不同类型的 var 数据(在我的情况下DataError)。我听说可能的解决方案是通过接口统一DataDataError结构化。或者也许有另一个更好的解决方案?

你能指出我如何解决这个问题吗?

谢谢

web*_*rc2 5

看起来您正在尝试创建一个联合类型(ML 系列语言称之为“枚举”)。我知道这有几种模式:

0. 基本错误处理(playground

我怀疑你在做什么只是基本的错误处理。在 Go 中,我们使用多个返回值并检查结果。这几乎肯定是您想要做的:

package main

import (
    "fmt"
    "log"
)

type Data struct {
    ID   int
    Name string
}

type DataError struct {
    Message   string
    ErrorCode string
}

// Implement the `error` interface. `error` is an interface with
// a single `Error() string` method
func (err DataError) Error() string {
    return fmt.Sprintf("%s: %s", err.ErrorCode, err.Message)
}

func SomeFunction(returnData bool) (Data, error) {
    if returnData {
        return Data{ID: 42, Name: "Answer"}, nil
    }
    return Data{}, DataError{
        Message:   "A thing happened",
        ErrorCode: "Oops!",
    }
}

func main() {
    // this bool argument controls whether or not an error is returned
    data, err := SomeFunction(false)
    if err != nil {
        log.Fatalln(err)
    }
    fmt.Println(data)
}
Run Code Online (Sandbox Code Playgroud)

1. 接口(游乐场

同样,如果您的选项是好的数据和错误,您可能应该使用第一种情况(坚持习惯用法/约定),但其他时候您可能有多个“好的数据”选项。我们可以使用接口来解决这个问题。在这里,我们添加了一个虚拟方法来告诉编译器将可以实现此接口的可能类型限制为具有 IsResult() 方法的类型。最大的缺点是将东西放入接口可能会导致分配,这在紧密循环中可能是有害的。这种模式并不是很常见。

package main

import "fmt"

type Result interface {
    // a dummy method to limit the possible types that can
    // satisfy this interface
    IsResult()
}

type Data struct {
    ID   int
    Name string
}

func (d Data) IsResult() {}

type DataError struct {
    Message   string
    ErrorCode string
}

func (err DataError) IsResult() {}

func SomeFunction(isGoodData bool) Result {
    if isGoodData {
        return Data{ID: 42, Name: "answer"}
    }
    return DataError{Message: "A thing happened", ErrorCode: "Oops!"}
}

func main() {
    fmt.Println(SomeFunction(true))
}
Run Code Online (Sandbox Code Playgroud)

2. 标记联盟(playground

这种情况与前一种情况类似,除了不使用接口,我们使用带有标记的结构体,该标记告诉我们结构体包含哪种类型的数据(这类似于 C 中的标记联合,不同之处在于该结构是其潜在类型的总和,而不是其最大潜在类型的大小)。虽然这会占用更多空间,但它可以很容易地进行堆栈分配,从而使其对紧密循环友好(我已经使用这种技术将分配从 O(n) 减少到 O(1))。在这种情况下,我们的标签是 bool,因为我们只有两种可能的类型(Data 和 DataError),但您也可以使用类似 C 的枚举。

package main

import (
    "fmt"
)

type Data struct {
    ID   int
    Name string
}

type DataError struct {
    Message   string
    ErrorCode string
}

type Result struct {
    IsGoodData bool
    Data       Data
    Error      DataError
}

// Implements the `fmt.Stringer` interface; this is automatically
// detected and invoked by fmt.Println() and friends
func (r Result) String() string {
    if r.IsGoodData {
        return fmt.Sprint(r.Data)
    }
    return fmt.Sprint(r.Error)
}

func SomeFunction(isGoodData bool) Result {
    if isGoodData {
        return Result{
            IsGoodData: true,
            Data:       Data{ID: 42, Name: "Answer"},
        }
    }
    return Result{
        IsGoodData: false,
        Error: DataError{
            Message:   "A thing happened",
            ErrorCode: "Oops!",
        },
    }
}

func main() {
    // this bool argument controls whether or not an error is returned
    fmt.Println(SomeFunction(true))
}
Run Code Online (Sandbox Code Playgroud)