在Go中,如何获得结构的字符串表示形式? [英] In Go, how can I get the string representation of a struct?

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

问题描述

对于我的应用程序,字符串是否是人类可读的并不重要。

解决方案

一种流行的编码方式结构化为字符串使用 JSON



您可以确定诸如没有获得所有信息(诸如每个字段的特定类型),仅对输出字段进行序列化以及不处理递归值的限制。但是它是序列化数据的简单标准方式。



工作示例:

  b 




$ f
$ f $ $ b int int
字符串字符串
ByteSlice []字节
}

func main(){
a:=& s {42,Hello World!,[] byte {0,1,2,3,4}}
$ b $ 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


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

解决方案

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.

Working example:

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))
}

Give this output:

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

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

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

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