Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print struct variables in console?

Tags:

struct

go

How can I print (to the console) the Id, Title, Name, etc. of this struct in Golang?

type Project struct {     Id      int64   `json:"project_id"`     Title   string  `json:"title"`     Name    string  `json:"name"`     Data    Data    `json:"data"`     Commits Commits `json:"commits"` } 
like image 364
fnr Avatar asked Jul 01 '14 13:07

fnr


People also ask

How do you print a string in a struct?

Instead, you should pass the address of the first character of the string which is: scanf("%s %d", &(tempname[0]), &temptel); or more simply: scanf("%s %d", tempname, &temptel);

How do I print a variable in go?

To print a variable's type, you can use the %T verb in the fmt. Printf() function format. It's the simplest and most recommended way of printing type of a variable. Alternatively, you can use the TypeOf() function from the reflection package reflect .


2 Answers

To print the name of the fields in a struct:

fmt.Printf("%+v\n", yourProject) 

From the fmt package:

when printing structs, the plus flag (%+v) adds field names

That supposes you have an instance of Project (in 'yourProject')

The article JSON and Go will give more details on how to retrieve the values from a JSON struct.


This Go by example page provides another technique:

type Response2 struct {   Page   int      `json:"page"`   Fruits []string `json:"fruits"` }  res2D := &Response2{     Page:   1,     Fruits: []string{"apple", "peach", "pear"}} res2B, _ := json.Marshal(res2D) fmt.Println(string(res2B)) 

That would print:

{"page":1,"fruits":["apple","peach","pear"]} 

If you don't have any instance, then you need to use reflection to display the name of the field of a given struct, as in this example.

type T struct {     A int     B string }  t := T{23, "skidoo"} s := reflect.ValueOf(&t).Elem() typeOfT := s.Type()  for i := 0; i < s.NumField(); i++ {     f := s.Field(i)     fmt.Printf("%d: %s %s = %v\n", i,         typeOfT.Field(i).Name, f.Type(), f.Interface()) } 
like image 81
VonC Avatar answered Nov 01 '22 23:11

VonC


I want to recommend go-spew, which according to their github "Implements a deep pretty printer for Go data structures to aid in debugging"

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

usage example:

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:

(main.Project) {  Id: (int64) 0,  Title: (string) (len=5) "world",  Name: (string) (len=5) "hello",  Data: (string) "",  Commits: (string) "" } 
like image 28
Martin Olika Avatar answered Nov 01 '22 22:11

Martin Olika