英文:
Is there a function in Go to print all the current member names and values of an object?
问题
我正在寻找类似于PHP的print_r或Python的__dict__的功能。有人知道是否存在这样的函数,还是需要自己实现?
英文:
I'm looking for something like PHP's print_r or python's dict. Anybody know if this function exists, or its something that needs to be implemented?
答案1
得分: 4
在Go语言中有一个reflect
包。
你可以在以下的文章中找到解决你问题的方法。
英文:
There is a reflect
package in go.
You can find solution to your problem in the following article.
答案2
得分: 3
对于打印原生的go对象,比如maps、slices和arrays,你可以尝试使用:
fmt.Printf("%v", object)
然而,对于用户自定义的结构体类型,目前还没有通用的方法来实现。
英文:
For printing native go objects, like maps, slices, and arrays, you can try:
fmt.Printf("%v", object)
However there isn't a general method to do it with user-defined struct types..
答案3
得分: 2
尝试使用以下代码:
fmt.Printf("%+v", object)
这可能会给你一个类似你想要的结果的东西。
英文:
Try
fmt.Printf("%+v", object)
That might give you something resembling what you want.
答案4
得分: 1
你可以尝试使用dump
包,它类似于PHP的print_r
或var_dump
。
然后只需调用dump.Dump(yourObject)
或dump.Fdump(file, yourObject)
。
英文:
You can try using the package dump
, which acts similar to PHP's print_r
or var_dump
.
The sources are here and the main project page is here.
Then just call dump.Dump(yourObject)
or dump.Fdump(file, yourObject)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论