乐闻世界logo
搜索文章和话题

How to print struct variables in console on golang

3个答案

1
2
3

In Go, to print struct variables in the console, you can use the Println or Printf functions from the fmt package. Additionally, for a more readable output of struct contents, you can use the %+v format specifier, which outputs struct information with field names and corresponding values. If you need full control over the output format, you might implement the String() method to customize the string representation. Here is a simple example:

First, define a struct:

go
package main import ( "fmt" ) // Define an example struct type Person struct { Name string Age int City string }

Then, create a struct instance and print it:

go
func main() { // Create a struct instance p := Person{ Name: "Alice", Age: 25, City: "New York", } // Use the fmt package to print the struct // %+v prints struct information with field names and values fmt.Printf("Person: %+v\n", p) // Alternatively, using fmt.Println prints the struct's values without field names fmt.Println("Person:", p) // For more customized output, implement the String method fmt.Println(p.String()) } // Implement the String method to customize the string representation of Person func (p Person) String() string { return fmt.Sprintf("Name: %s, Age: %d, City: %s", p.Name, p.Age, p.City) }

When you run this code, the console will output:

shell
Person: {Name:Alice Age:25 City:New York} Person: {Alice 25 New York} Name: Alice, Age: 25, City: New York

In the first Printf, the %+v format specifier prints each field name and its corresponding value. When using Println, only the struct's values are printed without field names. Finally, by implementing the String() method, you achieve a fully customized output format.

2024年6月29日 12:07 回复

I believe that if you want formatted output, it's better to implement a custom String method for the struct.

For example,

go
package main import "fmt" type Project struct { Id int64 `json:"project_id"` Title string `json:"title"` Name string `json:"name"` } func (p Project) String() string { return fmt.Sprintf("{Id:%d, Title:%s, Name:%s}", p.Id, p.Title, p.Name) } func main() { o := Project{Id: 4, Name: "hello", Title: "world"} fmt.Printf("%+v\n", o) }
2024年6月29日 12:07 回复

I recommend go-spew, according to their GitHub description: 'Implement a deep pretty printer for Go data structures to help with debugging.'

shell
go get -u github.com/davecgh/go-spew/spew

Usage Example:

shell
package main import ( "github.com/davecgh/go-spew/spew" ) type Project struct { Id int64 `json:"project_id"` Title string `json:"title"` Name string `json:"name"` Data string `json:"data"` Commits string `json:"commits"` } func main() { o := Project{Name: "hello", Title: "world"} spew.Dump(o) }

Output:

shell
(main.Project) { Id: (int64) 0, Title: (string) (len=5) "world", Name: (string) (len=5) "hello", Data: (string) "", Commits: (string) "" }
2024年6月29日 12:07 回复

你的答案