Home > Backend Development > Golang > How Can I Pretty Print Variables in Go?

How Can I Pretty Print Variables in Go?

Barbara Streisand
Release: 2024-12-04 02:57:10
Original
235 people have browsed it

How Can I Pretty Print Variables in Go?

Pretty Printing Variables in Go

Ruby's awesome_print function provides a convenient way to format and print variables. However, Go does not have a built-in equivalent. So, let's explore a couple of alternatives.

Using Printf:

The Printf function takes a format string as its first argument. By specifying the #v format for the variable, you can print its value in a human-readable format.

1

2

x := map[string]int{"a": 1, "b": 2}

fmt.Printf("%#v", x)

Copy after login

This will print the following output:

1

map[string]int{"a":1,"b":2}

Copy after login

However, this format does not provide indentation or line breaks.

Using json.MarshalIndent:

To obtain a more visually appealing format, you can use json.MarshalIndent. This function takes a value as input and returns its JSON representation with customizable indentation and line breaks.

1

2

3

4

5

6

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 following output:

1

2

3

4

{

    "a": 1,

    "b": 2

}

Copy after login

json.MarshalIndent is a suitable alternative to awesome_print for pretty printing variables in Go. It allows for customization of the indentation and line breaks, resulting in a visually pleasing output.

The above is the detailed content of How Can I Pretty Print Variables in Go?. 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