Print an array of empty interfaces in golang?

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

Print an array of empty interfaces in golang?

问题

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

以下是代码示例:

type MyType struct {
    field []interface{}
}
myType := //创建一个MyType。Field只是一个数字数组
println(myType.field) // 打印一个指针引用,例如:[1/1]0xc420269aa0
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:

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

How do I print the values in myType.field?

答案1

得分: 1

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

func dump(items []interface{}) {
	for i := 0; i < len(items); i++ {
		fmt.Println(items[i])
	}
}
// 或者
fmt.Println(items)
英文:

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

func dump(items []interface{}) {
 for i := 0; i &lt; len(items); i++ {
	fmt.Println(items[i])
   }
}
// OR
fmt.Println(items)

答案2

得分: 0

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

questionSet := []interface{}{} 

// ... 用代码填充问题集合

fmt.Printf("%t", questionSet)

以下是结果:

[%!t(*domain.Question=&{第一个经济学问题3 
[{学生的经济学选项1 false} 
{学生的经济学选项2 false} 
{学生的经济学选项3 true} 
{学生的经济学选项4 false}] 
[{经济学第一个主题} {经济学第二个主题}]}) 

%!t(*domain.Question=&{第二个问题4 
[{学生的问题2选项1 false} 
{学生的问题2选项2 false} 
{学生的问题2选项3 false} 
{学生的问题2选项4 false}] 
[{第三个主题} {第四个主题}]})]

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

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

type Question struct {
	Questions string            `json:"questions,omitempty" bson:"questions"`
	Marks     string            `json:"marks,omitempty" bson:"marks"`
	Options   []QuestionOptions `json:"options,omitempty" bson:"options"`
	Topics    []QuestionTopic   `json:"topics,omitempty" bson:"topics"`
}

type QuestionOptions struct {
	Option  string `json:"option" bson:"option"`
	Correct bool   `json:"correct" bson:"correct"`
}

type QuestionTopic struct {
	Topic string `json:"topic" bson:"topic"`
}

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

祝一切顺利,

英文:

Array interfaces can be printed as follows

questionSet := []interface{}{} 

// ... code to fillup the question set

fmt.Printf(&quot;%t&quot;, questionSet)

and here is the result

[%!t(*domain.Question=&amp;{First Economics question 3 
[{Economics option 1 for student false} 
{Economics option 2 for student false} 
{Economics option 3 for student true} 
{Economics option 4 for student false}] 
[{Economics first topic} {Economics second topic}]}) 

%!t(*domain.Question=&amp;{second Question 4 
[{Qs2 Option 1 for student false} 
{Qs2 Option 2 for student false} 
{Qs2 Option 3 for student false} 
{Qs2 Option 4 for student false}] 
[{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.

type Question struct {
	Questions string            `json:&quot;questions,omitempty&quot; bson:&quot;questions&quot;`
	Marks     string            `json:&quot;marks,omitempty&quot; bson:&quot;marks&quot;`
	Options   []QuestionOptions `json:&quot;options,omitempty&quot; bson:&quot;options&quot;`
	Topics    []QuestionTopic   `json:&quot;topics,omitempty&quot; bson:&quot;topics&quot;`
}

type QuestionOptions struct {
	Option  string `json:&quot;option&quot; bson:&quot;option&quot;`
	Correct bool   `json:&quot;correct&quot; bson:&quot;correct&quot;`
}

type QuestionTopic struct {
	Topic string `json:&quot;topic&quot; bson:&quot;topic&quot;`
}

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

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

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	fmt.Println(dump(new(bool)))
	fmt.Println(dump([]interface{}{new(bool), new(string)}))
}

func dump(x interface{}) string {
	json, err := json.MarshalIndent(x, "", "  ")
	if err != nil {
		panic(err)
	}

	return string(json)
}
// 输出:
// false
// [
//   false,
//   ""
// ]

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

英文:

another way you could use

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

package main

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

func main() {
	fmt.Println(dump(new(bool)))
	fmt.Println(dump([]interface{}{new(bool), new(string)}))
}

func dump(x interface{}) string {
	json, err := json.MarshalIndent(x, &quot;&quot;, &quot;  &quot;)
	if err != nil {
		panic(err)
	}

	return string(json)
}
// Outputs:
// false
// [
//   false,
//   &quot;&quot;
// ]

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:

确定