¿Cómo imprimir variables de estructura en la consola?
¿Cómo puedo imprimir (en la consola) el Id
, Title
, Name
, etc. de esta estructura en 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"`
}
13 answers
Para imprimir el nombre de los campos en una estructura:
fmt.Printf("%+v\n", yourProject)
De la fmt
paquete :
Al imprimir estructuras, la bandera más (
%+v
) agrega nombres de campo
Que supone que tienes una instancia de Proyecto (en 'yourProject
')
El artículo JSON y Go darán más detalles sobre cómo recuperar los valores de una estructura JSON.
Este Ir por página de ejemplo proporciona otra técnica:
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))
Eso sería print:
{"Page":1,"Fruits":["apple","peach","pear"]}
Si no tienes ninguna instancia, entonces necesitas utilizar la reflexión para mostrar el nombre del campo de una estructura dada, como en este ejemplo.
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())
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-01 14:19:50
Quiero recomendar go-spew , que según su github "Implementa una impresora bastante profunda para estructuras de datos Go para ayudar en la depuración"
go get -u github.com/davecgh/go-spew/spew
Ejemplo de uso:
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)
}
Salida:
(main.Project) {
Id: (int64) 0,
Title: (string) (len=5) "world",
Name: (string) (len=5) "hello",
Data: (string) "",
Commits: (string) ""
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-23 17:33:14
Creo que sería mejor implementar un stringer personalizado si desea algún tipo de salida formateada de un struct
Por ejemplo
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)
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-03 06:16:30
p = Project{...}
fmt.Printf("%+v", p)
fmt.Printf("%#v", p) //with type
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-03 03:09:42
Mis 2cents serían usar json.MarshalIndent
surprised me sorprende que esto no se sugiera, ya que es el más sencillo. por ejemplo:
func prettyPrint(i interface{}) string {
s, _ := json.MarshalIndent(i, "", "\t")
return string(s)
}
No hay deps externos y resulta en una salida bien formateada.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-10 16:24:48
Visita aquí para ver el código completo. Aquí también encontrará un enlace para un terminal en línea donde se puede ejecutar el código completo y el programa representa cómo extraer la información de la estructura(nombre del campo su tipo y valor). A continuación se muestra el fragmento de código del programa que solo imprime los nombres de los campos.
package main
import "fmt"
import "reflect"
func main() {
type Book struct {
Id int
Name string
Title string
}
book := Book{1, "Let us C", "Enjoy programming with practice"}
e := reflect.ValueOf(&book).Elem()
for i := 0; i < e.NumField(); i++ {
fieldName := e.Type().Field(i).Name
fmt.Printf("%v\n", fieldName)
}
}
/*
Id
Name
Title
*/
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-18 09:10:19
Recomiendo usar Pretty Printer Library. En el que puede imprimir cualquier estructura muy fácilmente.
-
Instalar biblioteca
O
go get github.com/kr/pretty
Ahora haz así en tu código
package main
import (
fmt
github.com/kr/pretty
)
func main(){
type Project struct {
Id int64 `json:"project_id"`
Title string `json:"title"`
Name string `json:"name"`
Data Data `json:"data"`
Commits Commits `json:"commits"`
}
fmt.Printf("%# v", pretty.Formatter(Project)) //It will print all struct details
fmt.Printf("%# v", pretty.Formatter(Project.Id)) //It will print component one by one.
}
También se puede obtener la diferencia entre los componentes a través de esta biblioteca y así más. También puede echar un vistazo a library Docs aquí.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-20 09:59:33
También está go-render, que maneja la recursividad del puntero y mucha clasificación de teclas para los mapas de cadena e int.
Instalación:
go get github.com/luci/go-render/render
Ejemplo:
type customType int
type testStruct struct {
S string
V *map[string]int
I interface{}
}
a := testStruct{
S: "hello",
V: &map[string]int{"foo": 0, "bar": 1},
I: customType(42),
}
fmt.Println("Render test:")
fmt.Printf("fmt.Printf: %#v\n", a)))
fmt.Printf("render.Render: %s\n", Render(a))
Que imprime:
fmt.Printf: render.testStruct{S:"hello", V:(*map[string]int)(0x600dd065), I:42}
render.Render: render.testStruct{S:"hello", V:(*map[string]int){"bar":1, "foo":0}, I:render.customType(42)}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-15 20:42:06
Me gusta camada.
De su readme:
type Person struct {
Name string
Age int
Parent *Person
}
litter.Dump(Person{
Name: "Bob",
Age: 20,
Parent: &Person{
Name: "Jane",
Age: 50,
},
})
Sdump
es bastante útil en las pruebas:
func TestSearch(t *testing.T) {
result := DoSearch()
actual := litterOpts.Sdump(result)
expected, err := ioutil.ReadFile("testdata.txt")
if err != nil {
// First run, write test data since it doesn't exist
if !os.IsNotExist(err) {
t.Error(err)
}
ioutil.Write("testdata.txt", actual, 0644)
actual = expected
}
if expected != actual {
t.Errorf("Expected %s, got %s", expected, actual)
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-16 11:29:47
Otra forma es, crear un func llamado toString
que toma struct, formatear el
campos como desee.
import (
"fmt"
)
type T struct {
x, y string
}
func (r T) toString() string {
return "Formate as u need :" + r.x + r.y
}
func main() {
r1 := T{"csa", "ac"}
fmt.Println("toStringed : ", r1.toString())
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-18 10:48:05
Quiero recomendar Stuct Example GO language program con un ejemplo de tipo Struc.
package main import ( "fmt" ) func main() { type Salary struct{ Basic, HRA, TA float64 } type Employee struct{ FirstName, LastName, Email string Age int MonthlySalary []Salary } e := Employee{ FirstName: "Mark", LastName: "Jones", Email: "[email protected]", Age: 25, MonthlySalary: []Salary{ Salary{ Basic:15000.00, HRA:5000.00, TA:2000.00, }, Salary{ Basic:16000.00, HRA:5000.00, TA:2100.00, }, Salary{ Basic:17000.00, HRA:5000.00, TA:2200.00, }, }, } fmt.Println(e.FirstName,e.LastName) fmt.Println(e.Age) fmt.Println(e.Email) fmt.Println(e.MonthlySalary[0]) fmt.Println(e.MonthlySalary[1]) fmt.Println(e.MonthlySalary[2]) }
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-16 14:54:43
Sin usar bibliotecas externas y con una nueva línea después de cada campo:
log.Println(
strings.Replace(
fmt.Sprintf("%#v", post), ", ", "\n", -1))
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-21 08:13:02
Cuando tenga estructuras más complejas, es posible que necesite convertir a JSON antes de imprimir:
// Convert structs to JSON.
data, err := json.Marshal(myComplexStruct)
if err != nil {
log.Fatal(
}
fmt.Printf("%s\n", data)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-23 14:33:12