Print an array of empty interfaces in golang?

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

Print an array of empty interfaces in golang?

问题

我有一个包含field []interface{}形式字段的结构体。如果我打印该字段,我会得到一个指针引用。如果我尝试解引用该字段,我会得到一个"invalid indirect"错误。

以下是代码示例:

  1. type MyType struct {
  2. field []interface{}
  3. }
  4. myType := //创建一个MyType。Field只是一个数字数组
  5. println(myType.field) // 打印一个指针引用,例如:[1/1]0xc420269aa0
  6. println(*(myType.field)) // 无法编译

如何打印myType.field中的值?

英文:

I have a struct with a field of the form field []interface{}. If I print the field, I get back a pointer reference. If I try to dereference the field, I get an error "invalid indirect".

The code is below:

  1. type MyType struct {
  2. field []interface{}
  3. }
  4. myType := //create a MyType. Field is just an array of numbers
  5. println(myType.field) // prints a pointer reference, ex: [1/1]0xc420269aa0
  6. println(*(myType.field)) // doesn't compile

How do I print the values in myType.field?

答案1

得分: 1

答案是通过循环遍历数组,或者更好地使用fmt.Println

  1. func dump(items []interface{}) {
  2. for i := 0; i < len(items); i++ {
  3. fmt.Println(items[i])
  4. }
  5. }
  6. // 或者
  7. fmt.Println(items)
英文:

The answer is to loop through the array, or even better, use fmt.Println.

  1. func dump(items []interface{}) {
  2. for i := 0; i &lt; len(items); i++ {
  3. fmt.Println(items[i])
  4. }
  5. }
  6. // OR
  7. fmt.Println(items)

答案2

得分: 0

数组接口可以按照以下方式打印:

  1. questionSet := []interface{}{}
  2. // ... 用代码填充问题集合
  3. fmt.Printf("%t", questionSet)

以下是结果:

  1. [%!t(*domain.Question=&{第一个经济学问题3
  2. [{学生的经济学选项1 false}
  3. {学生的经济学选项2 false}
  4. {学生的经济学选项3 true}
  5. {学生的经济学选项4 false}]
  6. [{经济学第一个主题} {经济学第二个主题}]})
  7. %!t(*domain.Question=&{第二个问题4
  8. [{学生的问题2选项1 false}
  9. {学生的问题2选项2 false}
  10. {学生的问题2选项3 false}
  11. {学生的问题2选项4 false}]
  12. [{第三个主题} {第四个主题}]})]

这里的输出可能不太美观,但至少你可以看到结果并提取相关信息进行进一步处理。

在上面的结果中,domain.Question是一个结构体,以下是完整的结构体供你参考。希望这能帮助你更好地理解。

  1. type Question struct {
  2. Questions string `json:"questions,omitempty" bson:"questions"`
  3. Marks string `json:"marks,omitempty" bson:"marks"`
  4. Options []QuestionOptions `json:"options,omitempty" bson:"options"`
  5. Topics []QuestionTopic `json:"topics,omitempty" bson:"topics"`
  6. }
  7. type QuestionOptions struct {
  8. Option string `json:"option" bson:"option"`
  9. Correct bool `json:"correct" bson:"correct"`
  10. }
  11. type QuestionTopic struct {
  12. Topic string `json:"topic" bson:"topic"`
  13. }

请注意,%t 是用来打印布尔值的动词(参见文档概述:https://golang.org/pkg/fmt/),尽管目前可以使用它来转储值的内容,但这不是 Go 作者预期的行为,因此这种行为可能会在将来发生变化。

祝一切顺利,

英文:

Array interfaces can be printed as follows

  1. questionSet := []interface{}{}
  2. // ... code to fillup the question set
  3. fmt.Printf(&quot;%t&quot;, questionSet)

and here is the result

  1. [%!t(*domain.Question=&amp;{First Economics question 3
  2. [{Economics option 1 for student false}
  3. {Economics option 2 for student false}
  4. {Economics option 3 for student true}
  5. {Economics option 4 for student false}]
  6. [{Economics first topic} {Economics second topic}]})
  7. %!t(*domain.Question=&amp;{second Question 4
  8. [{Qs2 Option 1 for student false}
  9. {Qs2 Option 2 for student false}
  10. {Qs2 Option 3 for student false}
  11. {Qs2 Option 4 for student false}]
  12. [{third topic} {fourth topic}]})]

The output here is not very pretty but at least you can see the result and extract your relevant information for further process.

In the above result domain.Question is a struct and here is the complete struct for your reference. Hope this will help you to understand better.

  1. type Question struct {
  2. Questions string `json:&quot;questions,omitempty&quot; bson:&quot;questions&quot;`
  3. Marks string `json:&quot;marks,omitempty&quot; bson:&quot;marks&quot;`
  4. Options []QuestionOptions `json:&quot;options,omitempty&quot; bson:&quot;options&quot;`
  5. Topics []QuestionTopic `json:&quot;topics,omitempty&quot; bson:&quot;topics&quot;`
  6. }
  7. type QuestionOptions struct {
  8. Option string `json:&quot;option&quot; bson:&quot;option&quot;`
  9. Correct bool `json:&quot;correct&quot; bson:&quot;correct&quot;`
  10. }
  11. type QuestionTopic struct {
  12. Topic string `json:&quot;topic&quot; bson:&quot;topic&quot;`
  13. }

Consider that the verb %t is designed to print boolean (see the doc overview at https://golang.org/pkg/fmt/), as such, while using it to dump the content of a value works as of today, it is not the behavior intended by go authors, and as such, this behavior might change in the future.

Peace,

答案3

得分: 0

另一种你可以使用的方法是:

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. func main() {
  7. fmt.Println(dump(new(bool)))
  8. fmt.Println(dump([]interface{}{new(bool), new(string)}))
  9. }
  10. func dump(x interface{}) string {
  11. json, err := json.MarshalIndent(x, "", " ")
  12. if err != nil {
  13. panic(err)
  14. }
  15. return string(json)
  16. }
  17. // 输出:
  18. // false
  19. // [
  20. // false,
  21. // ""
  22. // ]

请注意,这是一个Go语言的代码示例,它使用encoding/json包来将数据转换为JSON格式并进行缩进处理。dump函数接受一个任意类型的参数x,并返回其JSON表示形式的字符串。在main函数中,我们使用dump函数来打印出一个布尔值和一个包含布尔值和字符串的切片的JSON表示形式。

英文:

another way you could use

https://play.golang.org/p/4lLQ4Gb2S0m

  1. package main
  2. import (
  3. &quot;encoding/json&quot;
  4. &quot;fmt&quot;
  5. )
  6. func main() {
  7. fmt.Println(dump(new(bool)))
  8. fmt.Println(dump([]interface{}{new(bool), new(string)}))
  9. }
  10. func dump(x interface{}) string {
  11. json, err := json.MarshalIndent(x, &quot;&quot;, &quot; &quot;)
  12. if err != nil {
  13. panic(err)
  14. }
  15. return string(json)
  16. }
  17. // Outputs:
  18. // false
  19. // [
  20. // false,
  21. // &quot;&quot;
  22. // ]

huangapple
  • 本文由 发表于 2017年1月13日 03:52:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/41621805.html
匿名

发表评论

匿名网友

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

确定