如何获得结构的字符串表示形式? [英] How can I get the string representation of a struct?

查看:43
本文介绍了如何获得结构的字符串表示形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的应用程序,该字符串是否为人类可读都无关紧要.

For my application, it does not matter if the string is human readable or not.

推荐答案

一种将结构编码为字符串的流行方法是使用 JSON .

One popular way of encoding structs into strings is using JSON.

您有某些限制,例如无法获取所有信息(例如每个字段的特定类型),仅序列化导出的字段以及不处理递归值.但这是序列化数据的简单标准方法.

You have certain limitations such as not getting all the information (such as the specific type of each field), only serializing exported fields, and not handling recursive values. But it is a simple standard way of serializing data.

工作示例:

package main

import (
    "fmt"
    "encoding/json"
)

type s struct {
    Int       int
    String    string
    ByteSlice []byte
}

func main() {
    a := &s{42, "Hello World!", []byte{0,1,2,3,4}}

    out, err := json.Marshal(a)
    if err != nil {
        panic (err)
    }

    fmt.Println(string(out))
}

提供此输出:

{"Int":42,"String":"Hello World!","ByteSlice":"AAECAwQ="}

https://play.golang.org/p/sx-xdSxAOG

这篇关于如何获得结构的字符串表示形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆