美文网首页Golang语言社区golang
Go语言开发中空interface

Go语言开发中空interface

作者: 小歪子go | 来源:发表于2018-01-19 23:57 被阅读22次

做iOS开发的时候我们知道id指的是任意数据类型的对象,那么在Go语言开发有没有这样的数据类型,答案是肯定的,这种数据类型就是空interface,空interface(interface{})不包含任何的method,正因为如此,所有的类型都实现了空interface。空interface对于描述起不到任何的作用(因为它不包含任何的method),但是空interface在我们需要存储任意类型的数值的时候相当有用,因为它可以存储任意类型的数值。它有点类似于C语言的void*类型,OC中的id类型,但是oc中的id只能是引用类型,空interface既可以为引用类型也可以为值类型。

// 定义a为空接口
var a interface{}
var i int = 5
s := "Hello world"
// a可以存储任意类型的数值
a = i
a = s

在go语言的时候,当在一个方法的时候,不同条件返回不同的类型的数据,这时候用上空接口就很省事了,例如下面这段代码

// StructIPToAddress IP 到 地址
type StructIPToAddress struct {
    Address string `json:"address"`
    Content struct {
        Address       string `json:"address"`
        AddressDetail struct {
            City         string `json:"city"`
            CityCode     int64  `json:"city_code"`
            District     string `json:"district"`
            Province     string `json:"province"`
            Street       string `json:"street"`
            StreetNumber string `json:"street_number"`
            Point        struct {
                X string `json:"x"`
                Y string `json:"y"`
            } `json:"point"`
        } `json:"address_detail"`
    } `json:"content"`
    Status  int64  `json:"status"`
    Message string `json:"message"`
}
// requestBaidu 构建 HTTP 请求
func requestBaidu(reqType, reqURL string) (interface{}, error) {

    res, err := getResStruct(reqType)
    if err != nil {
        return res, err
    }
    httpClient := http.Client{}
    resp, err := httpClient.Get(reqURL)

    if err != nil {
        return res, err
    }

    defer resp.Body.Close()

    bytes, _ := ioutil.ReadAll(resp.Body)

    if resp.StatusCode == 200 {

        err := json.Unmarshal(bytes, &res)

        if err != nil {
            return res, err
        }

    } else {
        return res, errors.New("请求百度API失败,状态码不等于200")
    }

    return res, nil
}

// getResStruct 处理百度 API 返回数据,映射到结构体中
func getResStruct(reqType string) (interface{}, error) {
    var res interface{}

    if reqType == "GetAddressViaIP" {
        return new(StructIPToAddress), nil
    }

    if reqType == "GetGeoViaAddress" {
        return new(StructAddressToGEO), nil
    }

    if reqType == "GetAddressViaGEO" {
        return new(StructGEOToAddress), nil
    }
    return res, errors.New("结构体请求错误")
}

上面这段代码是以数据以空接口的形式返回,那么返回的数据如何转换呢,看下面这段代码

// GetAddressViaIP 通过 IP 获取地址
func GetAddressViaIP(address string) (*StructIPToAddress, error) {
    res := new(StructIPToAddress)
    parameter := fmt.Sprintf("&ip=%s&output=json&pois=0", address)
    reqURL := fmt.Sprintf("%s%s%s", reqURLForIP, AppKey, parameter)

    res2, err := requestBaidu("GetAddressViaIP", reqURL)
    if err != nil {
        return res, err
    }
    if res2.(*StructIPToAddress).Status != 0 {
        message := fmt.Sprintf("百度 API 报错:%s", res2.(*StructIPToAddress).Message)
        return res, errors.New(message)
    }

    res3 := res2.(*StructIPToAddress)
    return res3, nil

}

res2.(*StructIPToAddress)就是空接口转换成StructIPToAddress的写法

参考文档

查看interface介绍

相关文章

  • Go语言开发中空interface

    做iOS开发的时候我们知道id指的是任意数据类型的对象,那么在Go语言开发有没有这样的数据类型,答案是肯定的,这种...

  • interface in go

    interface是go语言定义的一种类型,通常用于定义一些方法的集合。但是在go语言里面,interface又与...

  • Go语言学习进度(7)

    1.GO语言关键字Interface 举例说明: 2.GO语言关键字defer

  • go进阶知识点讲解

    interface 底层实现 空interface 在Go语言的源码位置: src\runtime\runtime...

  • Go 语言 接口(Interface)

    What is Interface type in Go ? GoLang官网language specifica...

  • Go语言interface详解

    前言 Go语言里面设计最精妙的应该算interface,它让面向对象,内容组织实现非常的方便,当你看完这一章,你就...

  • Go语言接口——interface

    Go语言的Interface接口是一种神奇的特性。Interface包括了一组方法,同时也是一种类型。Interf...

  • Go语言接口interface

    Go 语言提供了另外一种数据类型即接口,它把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现...

  • golang关键字

    go语言关键字 package import func interface typestruct for ra...

  • Go语言之Interface(一)

    Go语言之Interface(一) 什么是interface 在面向对象语言中接口是:接口定义了一个对象的行为,但...

网友评论

    本文标题:Go语言开发中空interface

    本文链接:https://www.haomeiwen.com/subject/wuhzoxtx.html