{
  "slug": "Pretty-print-array-in-Golang--4c184f4517f6",
  "title": "Pretty print array in Golang.",
  "subtitle": "The simplest way to print an array or even interface in Golang is to write the below function.",
  "excerpt": "The simplest way to print an array or even interface in Golang is to write the below function.",
  "date": "2022-08-13",
  "tags": [
    "Go"
  ],
  "readingTime": "1 min",
  "url": "https://medium.com/@mobinshaterian/pretty-print-array-in-golang-4c184f4517f6",
  "hero": null,
  "content": [
    {
      "type": "heading",
      "level": 2,
      "text": "Pretty print array in Golang."
    },
    {
      "type": "paragraph",
      "html": "The simplest way to print an array or even interface in Golang is to write the below function."
    },
    {
      "type": "code",
      "lang": "go",
      "code": "func PrettyPrint(i interface{\n}) string {\n    s, _ := json.MarshalIndent(i, \"\", \"\\t\") fmt.Println(string(s)) return string(s)\n}"
    },
    {
      "type": "paragraph",
      "html": "Also we can define as struct in GO."
    },
    {
      "type": "code",
      "lang": "go",
      "code": "package prettyprint"
    },
    {
      "type": "code",
      "lang": "go",
      "code": "import (\n\"encoding/json\""
    },
    {
      "type": "code",
      "lang": "text",
      "code": "\"fmt\""
    },
    {
      "type": "code",
      "lang": "text",
      "code": ")"
    },
    {
      "type": "code",
      "lang": "javascript",
      "code": "var ("
    },
    {
      "type": "code",
      "lang": "go",
      "code": "PrettyPrint prettyPrintInterface = &prettyPrint{}"
    },
    {
      "type": "code",
      "lang": "text",
      "code": ")"
    },
    {
      "type": "code",
      "lang": "go",
      "code": "type prettyPrintInterface interface {"
    },
    {
      "type": "code",
      "lang": "go",
      "code": "Print(i interface{}) string"
    },
    {
      "type": "code",
      "lang": "text",
      "code": "}"
    },
    {
      "type": "code",
      "lang": "go",
      "code": "type prettyPrint struct {"
    },
    {
      "type": "code",
      "lang": "text",
      "code": "}"
    },
    {
      "type": "code",
      "lang": "go",
      "code": "func (p *prettyPrint) Print(i interface{\n}) string {"
    },
    {
      "type": "code",
      "lang": "go",
      "code": "s, _ := json.MarshalIndent(i, \"\", \"\\t\")"
    },
    {
      "type": "code",
      "lang": "go",
      "code": "fmt.Println(string(s))"
    },
    {
      "type": "code",
      "lang": "go",
      "code": "return string(s)"
    },
    {
      "type": "code",
      "lang": "text",
      "code": "}"
    }
  ]
}
