英文:
How to print struct variables in console?
问题
你可以使用fmt包中的Printf函数来打印Golang中结构体的Id
、Title
、Name
等字段到控制台。以下是一个示例代码:
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("%+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())
}
答案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 (
"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) ""
}
答案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, "", "\t")
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 "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)
}
答案5
得分: 27
p = 项目{...}
fmt.Printf("%+v", p)
fmt.Printf("%#v", p) //带有类型
英文:
p = Project{...}
fmt.Printf("%+v", p)
fmt.Printf("%#v", 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)
}
为了使用它,除了fmt
和encoding/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, "", "\t")
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%s \n", 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 = "10.1.1.0"
nw.Mask = 24
fmt.Println("### struct as a pointer ###")
PrettyPrint(&nw)
}
It's output would be
### struct as a pointer ###
{
"Network": "10.1.1.0",
"Mask": 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("%+v \n", yourProject)
if you want to see the full type of the sturct, you can use # replace + :
fmt.Printf("%#v \n", 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("%#v\n", s)
, It will print golang type at the same time
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)
}
result:
{Id:1 Title:title Name:jack}
main.Project{Id:1, Title:"title", Name:"jack"}
答案9
得分: 12
我建议使用漂亮的打印库。在这个库中,你可以非常容易地打印任何结构体。
或者
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.
-
Install Library
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:"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.
}
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: "Bob",
Age: 20,
Parent: &Person{
Name: "Jane",
Age: 50,
},
})
Sdump
is pretty handy in tests:
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)
}
}
答案11
得分: 8
将结构体以JSON格式打印出来的方法:
fmt.Printf("%#v\n", yourProject)
还可以使用以下方式(如上所述):
fmt.Printf("%+v\n", yourProject)
但是第二种选项会将字符串值打印出来时去除引号,所以阅读起来会更困难。
英文:
To print the struct as JSON:
fmt.Printf("%#v\n", yourProject)
Also possible with (as it was mentioned above):
fmt.Printf("%+v\n", 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 (
"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))
}
Output:
go run main.go
Project{Id: 1, Data: &ProjectData{
Title: "Test",
Name: "Mihai",
Data: "Some data",
Commits: "Test Message",
}}
答案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 "fmt"
import "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)
log.Printf("%s\n", 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("%s\n", data)
答案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 "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
*/
答案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: "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))
Which prints:
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)}
答案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, "", " ")
fmt.Println(string(marshalledText))
This results in formatting the data in json format with increased readability.
答案18
得分: 1
我建议使用json.Unmarshal()
函数。我尝试使用以下代码打印id,希望对你有帮助:
var jsonString = `{"Id": 1, "Title": "the title", "Name": "the name","Data": "the data","Commits" : "the commits"}`
var jsonData = []byte(jsonString)
var data Project
var err = json.Unmarshal(jsonData, &data)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println("Id :", data.Id)
请注意,这是一个示例代码,你需要根据自己的实际情况进行适当的修改。
英文:
i suggest to use json.Unmarshal()
i try to print the id with this hope its helpfull:
var jsonString = `{"Id": 1, "Title": "the title", "Name": "the name","Data": "the data","Commits" : "the commits"}`
var jsonData = []byte(jsonString)
var data Project
var err = json.Unmarshal(jsonData, &data)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println("Id :", data.Id)
答案19
得分: 0
fmt.Printf("%+v\n", project)
这是打印项目详情的基本方式。
英文:
fmt.Printf("%+v\n", 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 (
"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)
// Unmarshall and print the JSON keys and values
var dataMap map[string]string
err := json.Unmarshal(myProject.Data, &dataMap)
if err != nil {
fmt.Println("Error decoding Data:", err)
} else {
fmt.Println("Data: ", dataMap)
}
var commitsMap map[string]string
err = json.Unmarshal(myProject.Commits, &commitsMap)
if err != nil {
fmt.Println("Error decoding Commits:", err)
} else {
fmt.Println("Commits: ", 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("%#v", post), ", ", "\n", -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 (
"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)
}
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("Information %+v", 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 "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)
}
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:"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`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, &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 (
"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())
}
答案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("%+v", 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 = "%+v"
//In your code everywhere
fmt.Println(commons.STRUCTURE_DATA_FMT, structure variable)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论