Home >Backend Development >Golang >How Can I Pretty-Print Variables in Go Like Ruby's `awesome_print`?

How Can I Pretty-Print Variables in Go Like Ruby's `awesome_print`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-02 16:00:28978browse

How Can I Pretty-Print Variables in Go Like Ruby's `awesome_print`?

Printing Variables with Style in Go

Ruby's awesome_print Equivalent in Go

In Ruby, awesome_print provides a clean and structured way to display variables. Is there something similar in Go?

Solution

While there's no built-in equivalent, the json.MarshalIndent function offers a reasonable option.

x := map[string]interface{}{"a": 1, "b": 2}
b, err := json.MarshalIndent(x, "", "  ")
if err != nil {
    fmt.Println("error:", err)
}
fmt.Print(string(b))

This will print the variable x as a formatted JSON string:

{
    "a": 1,
    "b": 2
}

This solution does not require third-party packages, making it suitable for situations where external dependencies are undesirable.

The above is the detailed content of How Can I Pretty-Print Variables in Go Like Ruby's `awesome_print`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn