drwkqwa82140 2019-06-10 11:55 采纳率: 0%
浏览 164

如何在Golang中的struct中定义多种数据类型? [重复]

I have an HTTP request that I make, where the response is like so:

{
  "results": [
    {
      "gender": "male",
      "name": {
        "title": "mr",
        "first": "carter",
        "last": "roy"
      },
      "location": {
        "street": "8662 pine rd",
        "city": "minto",
        "state": "nova scotia",
        "postcode": "I8Q 4L3",
        "coordinates": {
          "latitude": "-65.0674",
          "longitude": "-174.1034"
        },
        "timezone": {
          "offset": "+8:00",
          "description": "Beijing, Perth, Singapore, Hong Kong"
        }
      },
      "email": "carter.roy@example.com",
      "login": {...},
      "dob": {
        "date": "1972-07-18T03:10:43Z",
        "age": 46
      },
      "registered": {
        "date": "2014-05-14T07:12:34Z",
        "age": 5
      },
      "phone": "174-802-7804",
      "cell": "194-903-4287",
      "id": {
        "name": "",
        "value": null
      },
      "picture": {
        "large": "https://randomuser.me/api/portraits/men/9.jpg",
        "medium": "https://randomuser.me/api/portraits/med/men/9.jpg",
        "thumbnail": "https://randomuser.me/api/portraits/thumb/men/9.jpg"
      },
      "nat": "CA"
    }
  ],
  "info": {...}
}

The response will always change every time you refresh the page.

The problem is, some fields (like postcode), will either be a string, or int, so how can one specify multiple types for a field like "postcode":

type Location struct {
    Street      string      `json:"street"`
    Postcode    string      `json:"postcode"`
    Coordinates Coordinates `json:"coordinates"`
}

Update

This is not a duplicate, because in my case I have two different data types for a field (i.e. string and int for postcode), so how can one specify this in a struct. I highly discourage looping through the raw data just for type checking.

</div>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
    • ¥15 微信会员卡接入微信支付商户号收款
    • ¥15 如何获取烟草零售终端数据
    • ¥15 数学建模招标中位数问题
    • ¥15 phython路径名过长报错 不知道什么问题
    • ¥15 深度学习中模型转换该怎么实现
    • ¥15 Stata外部命令安装问题求帮助!
    • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
    • ¥15 TYPCE母转母,插入认方向
    • ¥15 如何用python向钉钉机器人发送可以放大的图片?