Skip to content

Instantly share code, notes, and snippets.

@ededejr
Last active February 6, 2024 05:22
Show Gist options
  • Save ededejr/429ee80668970da7fbeb04e9c625a014 to your computer and use it in GitHub Desktop.
Save ededejr/429ee80668970da7fbeb04e9c625a014 to your computer and use it in GitHub Desktop.
Pretty print an interface in golang
package main
import (
"encoding/json"
"fmt"
)
func PrintInterface(i interface{}) error {
b, err := json.MarshalIndent(i, "", " ")
if err != nil {
return err
}
fmt.Println(string(b))
return nil
}

Usage:

func main() {
	m := map[string]interface{}{
		"name": "John",
		"age":  30,
		"pets": []string{"cat", "dog"},
	}

	err := PrintInterface(m)
	if err != nil {
		fmt.Println("Error:", err)
	}
}

Outputs:

{
  "age": 30,
  "name": "John",
  "pets": [
    "cat",
    "dog"
  ]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment