Golang接口?类型!

我们知道,实现一个接口所有方法,就是该接口。
但我认为,虽然golang用的interface{},翻译过来也是接口,但用类型来描述应该会更准确。下文我会用类型来描述interface{}。

我们首先定义一个Result类型,用以接收http的响应结果

result.go

type Result interface {
 Code() code   // service code Data() any    // response data Error() error // api/service error}

定义result,实现Result类型的方法

type result struct {
 code code data any err  error}

func (r *result) Code() code {
 return r.code}

func (r *result) Data() any {
 return r.data}

func (r *result) Error() error {
 return r.err}

定义code类型,实现Result类型的方法,并简单定义几个code

With方法用于捕获错误,并返回result对象

code.go

type code string

func (c code) Code() code {
 return c}

func (c code) Data() any {
 return nil}

func (c code) Error() error {
 return nil}

// With catch error
func (c code) With(err error) Result {
 return &result{ code: c, err:  err, }}

const (
 Success code = "0x0000" ErrInternalServerError code = "0x0010" ErrBadRequest          code = "0x0011")

定义Map,实现Result类型的方法

result.go

type Map map[string]any

func (m Map) Code() code {
 return Success}

func (m Map) Data() any {
 return m}

func (m Map) Error() error {
 return nil}

测试

因为result,code,Map都实现Result的所有方法,所以在方法中,我们可以返回这些对象给Result这一类型

func TestResult(t *testing.T) {
    err := os.ErrNotExist
    resultImplement := result.ErrInternalServerError.With(err)

    HandleResult(resultImplement)
    codeImplement := result.ErrBadRequest

    HandleResult(codeImplement)
    mapImplement := result.Map{
        "hello": "world",
    }
    HandleResult(mapImplement)
}

func HandleResult(rs result.Result) {
    if rs.Error() != nil || rs.Code() != result.Success{
        fmt.Printf("fail code: %s, error: %v\n", rs.Code(), rs.Error())
        return
    }
    fmt.Printf("success code: %s, data: %v\n", rs.Code(), rs.Data())
}

测试结果

fail code: 0x0010, error: file does not exist
fail code: 0x0011, error: <nil>
success code: 0x0000, data: map[hello:world]
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!