登录
首页 >  Golang >  Go问答

Go 中方法重写的示例是怎样的?

来源:stackoverflow

时间:2024-03-25 12:48:39 117浏览 收藏

Go 中方法重写是指自定义实现接口中的方法,以修改或扩展其行为。在给定的代码示例中,类型 Animal 实现了 json.Unmarshaler 和 json.Marshaler 接口。通过覆盖 UnmarshalJSON 和 MarshalJSON 方法,Animal 类型定义了如何将 JSON 数据编组为 Animal 值,以及如何将 Animal 值编组为 JSON 数据。这种方法重写允许自定义编组逻辑,以满足特定需求。

问题内容

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "strings"
)

type Animal int

const (
    Unknown Animal = iota
    Gopher
    Zebra
)

func (a *Animal) UnmarshalJSON(b []byte) error {
    var s string
    if err := json.Unmarshal(b, &s); err != nil {
        return err
    }
    switch strings.ToLower(s) {
    default:
        *a = Unknown
    case "gopher":
        *a = Gopher
    case "zebra":
        *a = Zebra
    }

    return nil
}

func (a Animal) MarshalJSON() ([]byte, error) {
    var s string
    switch a {
    default:
        s = "unknown"
    case Gopher:
        s = "gopher"
    case Zebra:
        s = "zebra"
    }

    return json.Marshal(s)
}

func main() {
    blob := `["gopher","armadillo","zebra","unknown","gopher","bee","gopher","zebra"]`
    var zoo []Animal
    if err := json.Unmarshal([]byte(blob), &zoo); err != nil {
        log.Fatal(err)
    }

    census := make(map[Animal]int)
    for _, animal := range zoo {
        census[animal] += 1
    }

    fmt.Printf("Zoo Census:\n* Gophers: %d\n* Zebras:  %d\n* Unknown: %d\n",
        census[Gopher], census[Zebra], census[Unknown])

}

这是 go doc 中 json 自定义编组示例的代码片段。我的问题是这段代码中对 marshaljson 和 unmarshaljson 方法的调用在哪里。这些方法是否以某种方式覆盖 json 包的 unmarshaljson 和 marshaljson 方法。我认为 go 不支持这种方式重写方法。请帮忙,我无法理解这段代码中发生了什么!!


正确答案


documentation says

在 json.unmarshal 实现中的某个地方,有类似这样的代码:

u, ok := v.(Unmarshaler)
 if ok {
     err := u.Unmarshal(data)
     if err != nil { /* handle error */}
 } else {
     // handle other kinds of values
 }

代码使用 type assertion 来确定该值是否满足 json.Unmarshaler 接口。如果该值确实满足该方法,则调用该值的 unmarshaljson 函数。

调用(*animal).unmarshaljson函数是因为*animal满足json.Unmarshaler接口。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《Go 中方法重写的示例是怎样的?》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>