Go中的排序接口

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

Sorting interface in Go

问题

我一直在谷歌和堆栈上寻找解决方案,但没有成功。

我正在将一个JSON文件导入到一个结构体中,但是当我想使用它时,值以随机顺序输出。这是我的JSON文件示例:

"Assets": {
    "asset1": "asset1.png",
    "asset2": "asset2.png"
  },
  "Colors": {
    "MainColor": [
      {
        "red": 247,
        "green": 0,
        "blue": 247
      }
    ],
    "MainGradient": [
      {
        "red": 9,
        "green": 103,
        "blue": 170
      },
      {
        "red": 18,
        "green": 138,
        "blue": 221
      }
    ]
}

我可以使用Unmarshal导入JSON,但是当我打印它时,"red, green, blue"的值以随机顺序输出,就像这样:

[{map[asset1:asset1.png asset2:asset2.png] {[map[red:247 green:0 blue:247]] [map[green:103 red:9 blue:170] map[green:138 blue:221 red:18]]}}]

如你所见,RGB值每次都以随机顺序出现。我想知道是否有一种方法可以始终按照相同的顺序输出:红色、绿色、蓝色。

谢谢。

英文:

Been googling and stacking around for the solution with no success.

I'm importing a JSON file to an struct, however, when I want to use it, the values come out in a random order. This is an example of my JSON file:

"Assets": {
    "asset1": "asset1.png",
    "asset2": "asset2.png"
  },
  "Colors": {
    "MainColor": [
      {
        "red": 247,
        "green": 0,
        "blue": 247
      }
    ],
    "MainGradient": [
      {
        "red": 9,
        "green": 103,
        "blue": 170
      },
      {
        "red": 18,
        "green": 138,
        "blue": 221
      }
    ]
}

I can import the JSON using Unmarshal, however, when I print it, the "red, green,blue" values outputs in random order, like this:

[{map[asset1:asset1.png asset2:asset2.png] {[map[red:247 green:0 blue:247]] [map[green:103 red:9 blue:170] map[green:138 blue:221 red:18]]}}]

As you can see, the RGB values come at random order every time. I want to know if there's a way to always output the in the same order: red, green, blue.

Thank you.

答案1

得分: 2

地图在Go语言中和JSON规范中都是无序的。你需要按照需要的顺序调用它们。

r, g, b := color["red"], color["green"], color["blue"]

你也可以将值解组成一个结构体,这样可以给你一个确定的布局:

type Color struct {
    Red   int `json:"red"`
    Green int `json:"green"`
    Blue  int `json:"blue"`
}

http://play.golang.org/p/0l01NxJ4dq

英文:

Maps are unordered, both in Go and per the JSON spec. You will have to call them in order as you need them.

r, g, b := color["red"], color["green"], color["blue"]

You can also unmarshal the values into a struct, which will give you a deterministic layout:

type Color struct {
	Red   int `json:"red"`
	Green int `json:"green"`
	Blue  int `json:"blue"`
}

http://play.golang.org/p/0l01NxJ4dq

答案2

得分: 0

我个人会选择JimB上面描述的方法,但另一个选项是只改变数据的显示方式。根据你的输出,我可以推断你使用了fmt.Printf("%v", YourInstance)。如果你使用格式化字符串明确指定每个项目的位置,那么映射中项目的顺序就不重要了,例如:

fmt.Printf("red: %v, green: %v, blue: %v\n", ColorInstance["red"], ColorInstance["green"], ColorInstance["blue"])

现在这只打印了一个实例,如果你想打印整个映射,你需要进一步的逻辑,但这是基本思路。

如果你希望按顺序排列,那么映射不适合你。如果你希望根据键快速访问,那么映射是一个不错的选择。如果你只是想将输出格式化为写入控制台或文件等,使用映射可以很容易地实现,但我个人认为,JimB的建议是处理反序列化和处理数据的最佳方式。我的理念是尽可能使结构具体化。你可以提前完成工作,以后的代码会更清晰、更简洁、性能更好。

英文:

While I personally would take the route JimB describes above another option is just to change how you display the data. I can infer based on your output that you did; fmt.Printf("%v", YourInstance). The order of the items in the map is irrelevant if you explicitly specify where each goes with a format string like;

fmt.Printf("red: %v, green: %v, blue: %v\n", ColorInstance["red"], ColorInstance["green"], ColorInstance["blue"])

Now that only prints a single instance so to print the whole thing you'd need further logic but that's the basic idea.

If you want things in order, a map is not the structure for you. If you want quick access based on a key, then a map is a good choice. If you just want to format your output for writing to console or a file or whatever, it can be done easily with a map but personally I think, JimB's suggestion is the best way to approach deserializing and processing data like that. My philosophy is to make the structures as concrete as possible. You get the work out of the way up front and have cleaner, more concise, better performing code there after.

huangapple
  • 本文由 发表于 2015年10月21日 03:40:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/33245431.html
匿名

发表评论

匿名网友

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

确定