如何在控制台中打印结构变量?

huangapple go评论85阅读模式
英文:

How to print struct variables in console?

问题

你可以使用fmt包中的Printf函数来打印Golang中结构体的IdTitleName等字段到控制台。以下是一个示例代码:

package main

import "fmt"

type Project struct {
    Id      int64   `json:"project_id"`
    Title   string  `json:"title"`
    Name    string  `json:"name"`
    Data    Data    `json:"data"`
    Commits Commits `json:"commits"`
}

type Data struct {
    // 定义Data结构体的字段
}

type Commits struct {
    // 定义Commits结构体的字段
}

func main() {
    project := Project{
        Id:    1,
        Title: "Project Title",
        Name:  "Project Name",
        Data: Data{
            // 初始化Data结构体的字段
        },
        Commits: Commits{
            // 初始化Commits结构体的字段
        },
    }

    fmt.Printf("Id: %d\n", project.Id)
    fmt.Printf("Title: %s\n", project.Title)
    fmt.Printf("Name: %s\n", project.Name)
    // 打印其他字段...

    // 输出结果到控制台
}

你可以根据需要打印结构体的其他字段,使用相应的格式化字符串进行打印。

英文:

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"`
}

答案1

得分: 1168

打印结构体字段的名称的方法如下:

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

根据fmt的说明:

当打印结构体时,加号标志(%+v)会添加字段名称。

这假设你有一个Project的实例(在yourProject中)。

文章JSON和Go将详细介绍如何从JSON结构中检索值的方法。


这个Go示例页面提供了另一种技术:

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))

这将打印:

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

如果你没有任何实例,那么你需要**使用反射**来显示给定结构体的字段名称,可以参考这个示例

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())
}
英文:

To print the name of the fields in a struct:

fmt.Printf(&quot;%+v\n&quot;, 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:&quot;page&quot;`
  Fruits []string `json:&quot;fruits&quot;`
}

res2D := &amp;Response2{
    Page:   1,
    Fruits: []string{&quot;apple&quot;, &quot;peach&quot;, &quot;pear&quot;}}
res2B, _ := json.Marshal(res2D)
fmt.Println(string(res2B))

That would print:

{&quot;page&quot;:1,&quot;fruits&quot;:[&quot;apple&quot;,&quot;peach&quot;,&quot;pear&quot;]}

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, &quot;skidoo&quot;}
s := reflect.ValueOf(&amp;t).Elem()
typeOfT := s.Type()

for i := 0; i &lt; s.NumField(); i++ {
	f := s.Field(i)
	fmt.Printf(&quot;%d: %s %s = %v\n&quot;, i,
		typeOfT.Field(i).Name, f.Type(), f.Interface())
}

答案2

得分: 209

我想推荐go-spew,根据他们的GitHub页面描述,它是一个用于Go数据结构的深度漂亮打印工具,用于调试。

安装方法:

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

使用示例:

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)
}

输出结果:

(main.Project) {
 Id: (int64) 0,
 Title: (string) (len=5) "world",
 Name: (string) (len=5) "hello",
 Data: (string) "",
 Commits: (string) ""
}
英文:

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 (
	&quot;github.com/davecgh/go-spew/spew&quot;
)

type Project struct {
	Id      int64  `json:&quot;project_id&quot;`
	Title   string `json:&quot;title&quot;`
	Name    string `json:&quot;name&quot;`
	Data    string `json:&quot;data&quot;`
	Commits string `json:&quot;commits&quot;`
}

func main() {

	o := Project{Name: &quot;hello&quot;, Title: &quot;world&quot;}
	spew.Dump(o)
}

output:

(main.Project) {
 Id: (int64) 0,
 Title: (string) (len=5) &quot;world&quot;,
 Name: (string) (len=5) &quot;hello&quot;,
 Data: (string) &quot;&quot;,
 Commits: (string) &quot;&quot;
}

答案3

得分: 196

我的建议是使用json.MarshalIndent函数进行格式化输出。这是最直接的方法。例如:

func prettyPrint(i interface{}) string {
    s, _ := json.MarshalIndent(i, "", "\t")
    return string(s)
}

这个方法不需要外部依赖,并且可以得到格式良好的输出结果。

英文:

my 2cents would be to use json.MarshalIndent -- surprised this isn't suggested, as it is the most straightforward. for example:

func prettyPrint(i interface{}) string {
	s, _ := json.MarshalIndent(i, &quot;&quot;, &quot;\t&quot;)
	return string(s)
}

no external deps and results in nicely formatted output.

答案4

得分: 49

我认为,如果你想要对struct进行格式化输出,最好实现一个自定义的字符串转换方法。

例如:

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)
}

你可以在Project结构体上定义一个String()方法,该方法返回一个格式化后的字符串。在main()函数中,通过fmt.Printf()函数使用%+v格式化输出o的值。

英文:

I think it would be better to implement a custom stringer if you want some kind of formatted output of a struct

for example

package main

    import &quot;fmt&quot;

    type Project struct {
        Id int64 `json:&quot;project_id&quot;`
        Title string `json:&quot;title&quot;`
        Name string `json:&quot;name&quot;`
    }

    func (p Project) String() string {
    	return fmt.Sprintf(&quot;{Id:%d, Title:%s, Name:%s}&quot;, p.Id, p.Title, p.Name)
    }

    func main() {
    	o := Project{Id: 4, Name: &quot;hello&quot;, Title: &quot;world&quot;}
    	fmt.Printf(&quot;%+v\n&quot;, o)
    }

答案5

得分: 27

p = 项目{...}
fmt.Printf("%+v", p)
fmt.Printf("%#v", p) //带有类型

英文:
p = Project{...}
fmt.Printf(&quot;%+v&quot;, p)
fmt.Printf(&quot;%#v&quot;, p) //with type

答案6

得分: 27

另外,尝试使用这个函数PrettyPrint()

// 打印对象的内容
func PrettyPrint(data interface{}) {
    var p []byte
    //    var err := error
    p, err := json.MarshalIndent(data, "", "\t")
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("%s \n", p)
}

为了使用它,除了fmtencoding/json这两个例外,你不需要任何额外的包,只需要引用、指针或者字面量来表示你创建的结构体。

要使用它,只需取出你的结构体,在main函数或者你所在的包中初始化它,并将其传递给PrettyPrint()函数。

type Prefix struct {
    Network string
    Mask    int
}

func valueStruct() {
    // 结构体作为值
    var nw Prefix
    nw.Network = "10.1.1.0"
    nw.Mask = 24
    fmt.Println("### 结构体作为指针 ###")
    PrettyPrint(&nw)
}

它的输出将会是

### 结构体作为指针 ###
{
    "Network": "10.1.1.0",
    "Mask": 24
}

在这里尝试运行代码:链接

英文:

Alternatively, try using this function PrettyPrint()

// print the contents of the obj
func PrettyPrint(data interface{}) {
	var p []byte
	//    var err := error
	p, err := json.MarshalIndent(data, &quot;&quot;, &quot;\t&quot;)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf(&quot;%s \n&quot;, p)
}

In order to use this you do not need any additional packages with the exception of fmt and encoding/json, just a reference, pointer to, or literal of the struct you have created.

To use just take your struct, initialize it in main or whatever package you are in and pass it into PrettyPrint().

type Prefix struct {
	Network string
	Mask    int
}

func valueStruct() {
	// struct as a value
	var nw Prefix
	nw.Network = &quot;10.1.1.0&quot;
	nw.Mask = 24
	fmt.Println(&quot;### struct as a pointer ###&quot;)
	PrettyPrint(&amp;nw)
}

It's output would be

### struct as a pointer ###
{
	&quot;Network&quot;: &quot;10.1.1.0&quot;,
	&quot;Mask&quot;: 24
} 

Play around with the code here.

答案7

得分: 16

使用包fmt输出非常方便:

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

如果你想查看结构体的完整类型,可以使用#替换+:

fmt.Printf("%#v \n", yourProject)
英文:

It is very convenient to use package fmt to output:

fmt.Printf(&quot;%+v \n&quot;, yourProject)

if you want to see the full type of the sturct, you can use # replace + :

fmt.Printf(&quot;%#v \n&quot;, yourProject) 

答案8

得分: 16

我建议您使用fmt.Printf("%#v\n", s),它可以同时打印出golang类型。

package main

import (
	"fmt"
    "testing"
)

type student struct {
	id   int32
	name string
}

type Project struct {
    Id      int64   `json:"project_id"`
    Title   string  `json:"title"`
    Name    string  `json:"name"`
}

func TestPrint(t *testing.T) {
	s := Project{1, "title","jack"}
	fmt.Printf("%+v\n", s)
	fmt.Printf("%#v\n", s)
}

结果:

{Id:1 Title:title Name:jack}
main.Project{Id:1, Title:"title", Name:"jack"}
英文:

I suggest u use fmt.Printf(&quot;%#v\n&quot;, s) , It will print golang type at the same time

package main

import (
	&quot;fmt&quot;
    &quot;testing&quot;
)

type student struct {
	id   int32
	name string
}

type Project struct {
    Id      int64   `json:&quot;project_id&quot;`
    Title   string  `json:&quot;title&quot;`
    Name    string  `json:&quot;name&quot;`
}

func TestPrint(t *testing.T) {
	s := Project{1, &quot;title&quot;,&quot;jack&quot;}
	fmt.Printf(&quot;%+v\n&quot;, s)
	fmt.Printf(&quot;%#v\n&quot;, s)
}

result:

{Id:1 Title:title Name:jack}
main.Project{Id:1, Title:&quot;title&quot;, Name:&quot;jack&quot;}

答案9

得分: 12

我建议使用漂亮的打印库。在这个库中,你可以非常容易地打印任何结构体。

  1. 安装库

    https://github.com/kr/pretty

或者

go get github.com/kr/pretty

现在在你的代码中这样做

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)) //它将打印所有结构体的详细信息

fmt.Printf("%#v", pretty.Formatter(Project.Id)) //它将逐个打印组件。

}

此外,你还可以通过这个库获取组件之间的差异等等。你也可以在这里查看库的文档

英文:

I recommend to use Pretty Printer Library. In that you can print any struct very easily.

  1. Install Library

    https://github.com/kr/pretty

or

go get github.com/kr/pretty

Now do like this in your code

package main

import (
fmt
github.com/kr/pretty
)

func main(){

type Project struct {
    Id int64 `json:&quot;project_id&quot;`
    Title string `json:&quot;title&quot;`
    Name string `json:&quot;name&quot;`
    Data Data `json:&quot;data&quot;`
    Commits Commits `json:&quot;commits&quot;`
}

fmt.Printf(&quot;%# v&quot;, pretty.Formatter(Project)) //It will print all struct details

fmt.Printf(&quot;%# v&quot;, pretty.Formatter(Project.Id)) //It will print component one by one.

}

Also you can get difference between component through this library and so more. You can also have a look on library Docs here.

答案10

得分: 10

我喜欢litter

从他们的自述文件中:

type Person struct {
  Name   string
  Age    int
  Parent *Person
}

litter.Dump(Person{
  Name:   "Bob",
  Age:    20,
  Parent: &Person{
    Name: "Jane",
    Age:  50,
  },
})

Sdump 在测试中非常方便:

func TestSearch(t *testing.T) {
  result := DoSearch()

  actual := litterOpts.Sdump(result)
  expected, err := ioutil.ReadFile("testdata.txt")
  if err != nil {
    // 第一次运行,写入测试数据,因为它不存在
    if !os.IsNotExist(err) {
      t.Error(err)
    }
    ioutil.Write("testdata.txt", actual, 0644)
    actual = expected
  }
  if expected != actual {
    t.Errorf("期望值为 %s,实际值为 %s", expected, actual)
  }
}
英文:

I like litter.

From their readme:

type Person struct {
  Name   string
  Age    int
  Parent *Person
}

litter.Dump(Person{
  Name:   &quot;Bob&quot;,
  Age:    20,
  Parent: &amp;Person{
    Name: &quot;Jane&quot;,
    Age:  50,
  },
})

Sdump is pretty handy in tests:

func TestSearch(t *testing.T) {
  result := DoSearch()

  actual := litterOpts.Sdump(result)
  expected, err := ioutil.ReadFile(&quot;testdata.txt&quot;)
  if err != nil {
    // First run, write test data since it doesn&#39;t exist
		if !os.IsNotExist(err) {
      t.Error(err)
    }
    ioutil.Write(&quot;testdata.txt&quot;, actual, 0644)
    actual = expected
  }
  if expected != actual {
    t.Errorf(&quot;Expected %s, got %s&quot;, expected, actual)
  }
}

答案11

得分: 8

将结构体以JSON格式打印出来的方法:

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

还可以使用以下方式(如上所述):

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

但是第二种选项会将字符串值打印出来时去除引号,所以阅读起来会更困难。

英文:

To print the struct as JSON:

fmt.Printf(&quot;%#v\n&quot;, yourProject)

Also possible with (as it was mentioned above):

fmt.Printf(&quot;%+v\n&quot;, yourProject)

But the second option prints string values without "" so it is harder to read.

答案12

得分: 6

有时候,将结构体打印为有效的Go代码(go/ast等效代码)可能会很方便。为此,https://github.com/hexops/valast 做得很好:

package main

import (
	"fmt"

	"github.com/hexops/valast"
)

type ProjectData struct {
	Title   string `json:"title"`
	Name    string `json:"name"`
	Data    string `json:"data"`
	Commits string `json:"commits"`
}

type Project struct {
	Id   int64        `json:"project_id"`
	Data *ProjectData `json:"data"`
}

func main() {
	p := Project{
		Id: 1,
		Data: &ProjectData{
			Title:   "Test",
			Name:    "Mihai",
			Data:    "Some data",
			Commits: "Test Message",
		},
	}
	fmt.Println(valast.String(p))
}

输出:

go run main.go 
Project{Id: 1, Data: &ProjectData{
        Title:   "Test",
        Name:    "Mihai",
        Data:    "Some data",
        Commits: "Test Message",
}}
英文:

Sometimes, it might be handy to print the struct as valid Go code (the go/ast equivalent). For this purpose, https://github.com/hexops/valast does a great job:

package main

import (
	&quot;fmt&quot;

	&quot;github.com/hexops/valast&quot;
)

type ProjectData struct {
	Title   string `json:&quot;title&quot;`
	Name    string `json:&quot;name&quot;`
	Data    string `json:&quot;data&quot;`
	Commits string `json:&quot;commits&quot;`
}

type Project struct {
	Id   int64        `json:&quot;project_id&quot;`
	Data *ProjectData `json:&quot;data&quot;`
}

func main() {
	p := Project{
		Id: 1,
		Data: &amp;ProjectData{
			Title:   &quot;Test&quot;,
			Name:    &quot;Mihai&quot;,
			Data:    &quot;Some data&quot;,
			Commits: &quot;Test Message&quot;,
		},
	}
	fmt.Println(valast.String(p))
}

Output:

go run main.go 
Project{Id: 1, Data: &amp;ProjectData{
        Title:   &quot;Test&quot;,
        Name:    &quot;Mihai&quot;,
        Data:    &quot;Some data&quot;,
        Commits: &quot;Test Message&quot;,
}}

答案13

得分: 6

你可以先对 JSON 进行编组(marshal),然后将其作为字符串打印出来。这样你就可以完整地看到整个结构体的值。

package main

import "fmt"
import "encoding/json"

type Project struct {
    Id    int64  `json:"project_id"`
    Title string `json:"title"`
    Name  string `json:"name"`
}

func main() {
    o := Project{Id: 4, Name: "hello", Title: "world"}
    om, _ := json.Marshal(o)
    fmt.Printf("%s\n", string(om))
}

请注意,我已经将 json.marshal 更正为 json.Marshal,并将 log.Printf 更正为 fmt.Printf

英文:

You can do the json mashal first and print it as a string. There you can see it the whole struct value completely.

package main

import &quot;fmt&quot;
import &quot;json&quot;

type Project struct {
    Id int64 `json:&quot;project_id&quot;`
    Title string `json:&quot;title&quot;`
    Name string `json:&quot;name&quot;`
}

func main() {
    o := Project{Id: 4, Name: &quot;hello&quot;, Title: &quot;world&quot;}
    om, _ := json.marshal(o)
    log.Printf(&quot;%s\n&quot;, string(om))
}

答案14

得分: 5

当你有更复杂的结构时,你可能需要在打印之前转换为JSON:

// 将结构体转换为JSON。
data, err := json.Marshal(myComplexStruct)
fmt.Printf("%s\n", data)

来源:https://gist.github.com/tetsuok/4942960

英文:

When you have more complex structures, you might need to convert to JSON before printing:

// Convert structs to JSON.
data, err := json.Marshal(myComplexStruct)
fmt.Printf(&quot;%s\n&quot;, data)

Source: https://gist.github.com/tetsuok/4942960

答案15

得分: 3

请点击这里查看完整的代码。在这里,你还会找到一个在线终端的链接,可以运行完整的代码,并且程序会展示如何提取结构体的信息(字段的名称、类型和值)。下面是只打印字段名称的程序片段。

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
*/
英文:

Visit <a href="https://gist.github.com/hygull/0fbc428dc77bef4a665b19d598f865d8">here</a> to see the complete code. Here you will also find a link for an online terminal where the complete code can be run and the program represents how to extract structure's information(field's name their type & value). Below is the program snippet that only prints the field names.

package main

import &quot;fmt&quot;
import &quot;reflect&quot;

func main() {
	type Book struct {
		Id    int
		Name  string
		Title string
	}

	book := Book{1, &quot;Let us C&quot;, &quot;Enjoy programming with practice&quot;}
	e := reflect.ValueOf(&amp;book).Elem()

	for i := 0; i &lt; e.NumField(); i++ {
		fieldName := e.Type().Field(i).Name
		fmt.Printf(&quot;%v\n&quot;, fieldName)
	}
}

/*
Id
Name
Title
*/

答案16

得分: 1

还有一个名为go-render的工具,它处理指针递归以及字符串和整数映射的大量键排序。

安装方法:

go get github.com/luci/go-render/render

示例代码:

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))

运行结果:

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)}
英文:

There's also go-render, which handles pointer recursion and lots of key sorting for string and int maps.

Installation:

go get github.com/luci/go-render/render

Example:

type customType int
type testStruct struct {
        S string
        V *map[string]int
        I interface{}
}

a := testStruct{
        S: &quot;hello&quot;,
        V: &amp;map[string]int{&quot;foo&quot;: 0, &quot;bar&quot;: 1},
        I: customType(42),
}

fmt.Println(&quot;Render test:&quot;)
fmt.Printf(&quot;fmt.Printf:    %#v\n&quot;, a)))
fmt.Printf(&quot;render.Render: %s\n&quot;, Render(a))

Which prints:

fmt.Printf:    render.testStruct{S:&quot;hello&quot;, V:(*map[string]int)(0x600dd065), I:42}
render.Render: render.testStruct{S:&quot;hello&quot;, V:(*map[string]int){&quot;bar&quot;:1, &quot;foo&quot;:0}, I:render.customType(42)}

答案17

得分: 1

也许这不适用于生产请求,但如果你处于调试模式,我建议你按照以下方法操作。

marshalledText, _ := json.MarshalIndent(inputStruct, "", " ")
fmt.Println(string(marshalledText))

这将以增加可读性的方式将数据格式化为 JSON 格式。

英文:

Maybe this shouldn't be applied for production requests but if you are on debugging mode I suggest you follow the below approach.

marshalledText, _ := json.MarshalIndent(inputStruct, &quot;&quot;, &quot; &quot;)
fmt.Println(string(marshalledText))

This results in formatting the data in json format with increased readability.

答案18

得分: 1

我建议使用json.Unmarshal()函数。我尝试使用以下代码打印id,希望对你有帮助:

var jsonString = `{&quot;Id&quot;: 1, &quot;Title&quot;: &quot;the title&quot;, &quot;Name&quot;: &quot;the name&quot;,&quot;Data&quot;: &quot;the data&quot;,&quot;Commits&quot; : &quot;the commits&quot;}`
var jsonData = []byte(jsonString)

var data Project

var err = json.Unmarshal(jsonData, &amp;data)
if err != nil {
    fmt.Println(err.Error())
    return
}

fmt.Println(&quot;Id :&quot;, data.Id)

请注意,这是一个示例代码,你需要根据自己的实际情况进行适当的修改。

英文:

i suggest to use json.Unmarshal()
i try to print the id with this hope its helpfull:

var jsonString = `{&quot;Id&quot;: 1, &quot;Title&quot;: &quot;the title&quot;, &quot;Name&quot;: &quot;the name&quot;,&quot;Data&quot;: &quot;the data&quot;,&quot;Commits&quot; : &quot;the commits&quot;}`
var jsonData = []byte(jsonString)

var data Project

var err = json.Unmarshal(jsonData, &amp;data)
if err != nil {
    fmt.Println(err.Error())
    return
}

fmt.Println(&quot;Id :&quot;, data.Id)

答案19

得分: 0

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

这是打印项目详情的基本方式。

英文:
fmt.Printf(&quot;%+v\n&quot;, project)

This is the basic way of printing the details

答案20

得分: 0

你甚至不需要动词。这将输出data中的所有内容:

fmt.Println(data)
英文:

You don't even need the verb. This dumps everything inside of data:

fmt.Println(data)

答案21

得分: 0

以下是翻译好的内容:

这里分享一个简单易懂的示例,用于独立访问Id、Title、Name、Data和Commits(假设Data和Commits是JSON格式):

package main

import (
  "fmt"
  "encoding/json"
)

type Project struct {
    Id      int64   `json:"project_id"`
    Title   string  `json:"title"`
    Name    string  `json:"name"`
    Data    json.RawMessage `json:"data"`
    Commits json.RawMessage `json:"commits"`
}

func main() {
  
    jsonDataStr := `{"key1":"value1", "key2":"value2"}`
    jsonData := []byte(jsonDataStr)
  
    jsonCommitStr := `{"commit1":"value1", "commit2":"value2"}`
    jsonCommits := []byte(jsonCommitStr)

    myProject := Project {
      Id: 101, 
      Title: "Trello", 
      Name: "Dashboard", 
      Data: jsonData,
      Commits: jsonCommits,
    }
  
    fmt.Println("ID: ", myProject.Id)
    fmt.Println("Title: ", myProject.Title)
    fmt.Println("Name: ", myProject.Name)

    // 解码并打印JSON的键和值
    var dataMap map[string]string
    err := json.Unmarshal(myProject.Data, &dataMap)
    if err != nil {
      fmt.Println("解码Data时出错:", err)
    } else {
      fmt.Println("Data: ", dataMap)
    }
    
    var commitsMap map[string]string
    err = json.Unmarshal(myProject.Commits, &commitsMap)
    if err != nil {
      fmt.Println("解码Commits时出错:", err)
    } else {
      fmt.Println("Commits: ", commitsMap)
    }
}

你可以将这段代码复制粘贴到 https://replit.com/languages/go ,它将输出以下结果:

ID:  101
Title:  Trello
Name:  Dashboard
Data:  map[key1:value1 key2:value2]
Commits:  map[commit1:value1 commit2:value2]
英文:

Sharing an easy to follow example here for accessing just the Id, Title, Name, Data and Commits independently (presuming Data and Commits are meant to be JSON):

package main

import (
  &quot;fmt&quot;
  &quot;encoding/json&quot;
)

type Project struct {
    Id      int64   `json:&quot;project_id&quot;`
    Title   string  `json:&quot;title&quot;`
    Name    string  `json:&quot;name&quot;`
    Data    json.RawMessage `json:&quot;data&quot;`
    Commits json.RawMessage `json:&quot;commits&quot;`
}

func main() {
  
    jsonDataStr := `{&quot;key1&quot;:&quot;value1&quot;, &quot;key2&quot;:&quot;value2&quot;}`
    jsonData := []byte(jsonDataStr)
  
    jsonCommitStr := `{&quot;commit1&quot;:&quot;value1&quot;, &quot;commit2&quot;:&quot;value2&quot;}`
    jsonCommits := []byte(jsonCommitStr)

    myProject := Project {
      Id: 101, 
      Title: &quot;Trello&quot;, 
      Name: &quot;Dashboard&quot;, 
      Data: jsonData,
      Commits: jsonCommits,
    }
  
    fmt.Println(&quot;ID: &quot;, myProject.Id)
    fmt.Println(&quot;Title: &quot;, myProject.Title)
    fmt.Println(&quot;Name: &quot;, myProject.Name)

    // Unmarshall and print the JSON keys and values
    var dataMap map[string]string
    err := json.Unmarshal(myProject.Data, &amp;dataMap)
    if err != nil {
      fmt.Println(&quot;Error decoding Data:&quot;, err)
    } else {
      fmt.Println(&quot;Data: &quot;, dataMap)
    }
    
    var commitsMap map[string]string
    err = json.Unmarshal(myProject.Commits, &amp;commitsMap)
    if err != nil {
      fmt.Println(&quot;Error decoding Commits:&quot;, err)
    } else {
      fmt.Println(&quot;Commits: &quot;, commitsMap)
    }
}

You can copy and paste this into https://replit.com/languages/go and it will print out the output as:

ID:  101
Title:  Trello
Name:  Dashboard
Data:  map[key1:value1 key2:value2]
Commits:  map[commit1:value1 commit2:value2]

答案22

得分: -1

不使用外部库,并在每个字段后添加换行符:

log.Println(
    strings.Replace(
        fmt.Sprintf("%#v", post), ", ", "\n", -1))
英文:

Without using external libraries and with new line after each field:

log.Println(
			strings.Replace(
				fmt.Sprintf(&quot;%#v&quot;, post), &quot;, &quot;, &quot;\n&quot;, -1))

答案23

得分: -1

非常简单
我没有Data和Commits的结构,所以我进行了更改

package main

import (
	"fmt"
)

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() {
	p := Project{
		1,
		"First",
		"Ankit",
		"your data",
		"Commit message",
	}
	fmt.Println(p)
}

你可以从这里学习:https://gobyexample.com/structs

英文:

very simple
I don't have the structure of Data and Commits So I changed the

package main

import (
	&quot;fmt&quot;
)

type Project struct {
    Id      int64   `json:&quot;project_id&quot;`
    Title   string  `json:&quot;title&quot;`
    Name    string  `json:&quot;name&quot;`
    Data    string  `json:&quot;data&quot;`
    Commits string  `json:&quot;commits&quot;`
}

func main() {
	p := Project{
	1,
	&quot;First&quot;,
	&quot;Ankit&quot;,
	&quot;your data&quot;,
	&quot;Commit message&quot;,
	}
	fmt.Println(p)
}

For learning you can take help from here : https://gobyexample.com/structs

答案24

得分: -1

如果你想要将内容写入日志文件,就像我之前搜索到的那样。那么你应该使用:

log.Infof("信息 %+v", 结构体)

注意:这种方法不适用于 log.Info 或 log.Debug。在这种情况下,将会打印出 "%v",并且会打印出结构体的所有值,但不会打印出键名/变量名。

英文:

If you want to write in a log file, as I was searching previously. Then you should use:

log.Infof(&quot;Information %+v&quot;, structure)

Note:: This will not work with log.Info or log.Debug. In this case, "%v" will get printed, and all the values of the structure will be printed without printing the key/variable name.

答案25

得分: -1

一个简单问题有很多答案。我也可以参与其中。

package main

import "fmt"

type Project struct {
    Id    int64  `json:"project_id"`
    Title string `json:"title"`
    Name  string `json:"name"`
    //Data    Data    `json:"data"`
    //Commits Commits `json:"commits"`
}

var (
    Testy Project
)

func dump_project(foo Project) {
    fmt.Println("== Dump Project Struct ====")
    fmt.Printf("Id: %d\n", foo.Id)
    fmt.Println("Title: ", foo.Title)
    fmt.Printf("Name: %v\n", foo.Name)
}

func main() {
    fmt.Println("hello from go")
    Testy.Id = 3
    Testy.Title = "yo"
    Testy.Name = "my name"
    fmt.Println(Testy)
    dump_project(Testy)
}

各种打印方法的输出结果:

hello from go
{3 yo my name}
== Dump Project Struct ===
Id: 3
Title:  yo
Name: my name
英文:

A lot of answers for a simple question. I might as well throw my hat in the ring.

package main

import &quot;fmt&quot;

type Project struct {
	Id    int64  `json:&quot;project_id&quot;`
	Title string `json:&quot;title&quot;`
	Name  string `json:&quot;name&quot;`
	//Data    Data    `json:&quot;data&quot;`
	//Commits Commits `json:&quot;commits&quot;`
}

var (
	Testy Project
)

func dump_project(foo Project) {
	fmt.Println(&quot;== Dump Project Struct ====&quot;)
	fmt.Printf(&quot;Id: %d\n&quot;, foo.Id)
	fmt.Println(&quot;Title: &quot;, foo.Title)
	fmt.Printf(&quot;Name: %v\n&quot;, foo.Name)
}

func main() {
	fmt.Println(&quot;hello from go&quot;)
	Testy.Id = 3
	Testy.Title = &quot;yo&quot;
	Testy.Name = &quot;my name&quot;
	fmt.Println(Testy)
	dump_project(Testy)
}

The output of the various print methods

hello from go
{3 yo my name}
== Dump Project Struct ====
Id: 3
Title:  yo
Name: my name

答案26

得分: -2

type Response struct {
UserId int json:"userId"
Id int json:"id"
Title string json:"title"
Body string json:"body"
}

func PostsGet() gin.HandlerFunc {
return func(c *gin.Context) {
xs, err := http.Get("https://jsonplaceholder.typicode.com/posts")
if err != nil {
log.Println("The HTTP request failed with error: ", err)
}
data, _ := ioutil.ReadAll(xs.Body)

    // 这将在控制台打印结构体
    fmt.Println(string(data))

    // 这是作为 API 响应发送的
    bytes := []byte(string(data))
    var res []Response
    json.Unmarshal(bytes, &res)

    c.JSON(http.StatusOK, res)
}

}

英文:
    type Response struct {
    	UserId int    `json:&quot;userId&quot;`
    	Id     int    `json:&quot;id&quot;`
    	Title  string `json:&quot;title&quot;`
    	Body   string `json:&quot;body&quot;`
    }
    
    func PostsGet() gin.HandlerFunc {
    	return func(c *gin.Context) {
    		xs, err := http.Get(&quot;https://jsonplaceholder.typicode.com/posts&quot;)
    		if err != nil {
    			log.Println(&quot;The HTTP request failed with error: &quot;, err)
    		}
    		data, _ := ioutil.ReadAll(xs`enter code here`.Body)


            // this will print the struct in console    		
            fmt.Println(string(data))

    
            // this is to send as response for the API
    		bytes := []byte(string(data))
    		var res []Response
    		json.Unmarshal(bytes, &amp;res)
    
    		c.JSON(http.StatusOK, res)
    	}
    }

答案27

得分: -3

另一种方法是创建一个名为toString的函数,该函数接受一个结构体,并按照您的要求格式化字段。

import (
	"fmt"
)

type T struct {
	x, y string
}

func (r T) toString() string {
	return "按需格式化:" + r.x + r.y
}

func main() {
	r1 := T{"csa", "ac"}
	fmt.Println("格式化后的字符串:", r1.toString())
}
英文:

Another way is, create a func called toString that takes struct, format the
fields as you wish.

import (
	&quot;fmt&quot;
)

type T struct {
	x, y string
}

func (r T) toString() string {
	return &quot;Formate as u need :&quot; + r.x + r.y
}

func main() {
	r1 := T{&quot;csa&quot;, &quot;ac&quot;}
	fmt.Println(&quot;toStringed : &quot;, r1.toString())
}

答案28

得分: -7

大部分这些包都依赖于reflect包来实现这些功能。

如何在控制台中打印结构变量?

fmt.Sprintf()使用的是标准库中的func (p *pp) printArg(arg interface{}, verb rune)函数。

转到第638行:https://golang.org/src/fmt/print.go

反射:

https://golang.org/pkg/reflect/

示例代码:

https://github.com/donutloop/toolkit/blob/master/debugutil/prettysprint.go

英文:

Most of these packages are relying on the reflect package to make such things possible.

如何在控制台中打印结构变量?

fmt.Sprintf() is using -> func (p *pp) printArg(arg interface{}, verb rune) of standard lib

Go to line 638 -> https://golang.org/src/fmt/print.go

Reflection:

https://golang.org/pkg/reflect/

Example code:

https://github.com/donutloop/toolkit/blob/master/debugutil/prettysprint.go

答案29

得分: -10

fmt.Println("%+v", 结构变量)

更好的方法是在一个名为"commons"(或其他名称)的包中创建一个全局常量,用于存储字符串"%+v",并在代码的各个地方使用它。

// 在commons包中
const STRUCTURE_DATA_FMT = "%+v"

// 在你的代码的各个地方
fmt.Println(commons.STRUCTURE_DATA_FMT, 结构变量)
英文:
fmt.Println(&quot;%+v&quot;, structure variable)

A better way to do this would be to create a global constant for the string "%+v" in a package called "commons"(maybe) and use it everywhere in your code

//In commons package
const STRUCTURE_DATA_FMT = &quot;%+v&quot;

//In your code everywhere
fmt.Println(commons.STRUCTURE_DATA_FMT, structure variable)

huangapple
  • 本文由 发表于 2014年7月1日 21:57:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/24512112.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定