golang 经验,package export, json

1、可见性。Packages里的首字母大写的变量表示是export的。struct中成员如果也要在package外用,那成员变量名首字母要大写。

2、json Decode时的大小写。

在使用encoding/json进行decode时,struct相关变量需要大写。例如我们有string

{"jsonrpc":"1.0","id":"curltext","method":"getblockchaininfo","params":[]}

需要decode,我们定义struct

type BtcRpcRequest struct {
	Jsonrpc string   `json:jsonrpc`
	Id      string   `json:id`
	Method  string   `json:method`
	Params  []interface{} `json:params` 
}

注意:json的字段首字母小写,在decode需要struct的变量首字母是大写的,所以要用tag标注出来。

如果还需要将BtcRpcRequest json.Marshal成json字符串,上面的结构需要改下,json后加上双引号

type BtcRpcRequest struct {
	Jsonrpc string        `json:"jsonrpc"`
	Id      string        `json:"id"`
	Method  string        `json:"method"`
	Params  []interface{} `json:"params"`
}

如果不要null的输出 ,加上omitempty option.

type BtcRpcRequest struct {
	Jsonrpc string        `json:"jsonrpc,omitempty"`
	Id      string        `json:"id,omitempty"`
	Method  string        `json:"method,omitempty"`
	Params  []interface{} `json:"params,omitempty"`
}

example:

package main

import (
	"log"
	"encoding/json"
    "strings"
)
type BtcRpcRequest struct {
	Jsonrpc string        `json:"jsonrpc,omitempty"`
	Id      string        `json:"id,omitempty"`
	Method  string        `json:"method,omitempty"`
	Params  []interface{} `json:"params,omitempty"`
}

func main () {
    dec := json.NewDecoder(strings.NewReader(string(`{"jsonrpc":"1.0","id":"curltext","method":"getblockchaininfo","params":[]}`)))
    var m BtcRpcRequest
	err := dec.Decode(&m)
	if err != nil {
		log.Fatal(err)
	}
    log.Println(m)
    e, err := json.Marshal(&m)
	if err != nil {
		log.Fatal(err)
	}
    log.Println(string(e))
}

3、func (b BlockHeader) String() string { 。   String函数的object receiver不能用指针形式。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FatherOfCodingMan

如果觉得有用的话,可以赏点饭钱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值