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
Release: 2024-12-02 16:00:28
Original
1034 people have browsed it

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))
Copy after login

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

{
    "a": 1,
    "b": 2
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template