Skip to content

Instantly share code, notes, and snippets.

@aichaoxy
Created May 19, 2023 02:14
Show Gist options
  • Save aichaoxy/fe85a3e9729e157f525fe7a21fae60b4 to your computer and use it in GitHub Desktop.
Save aichaoxy/fe85a3e9729e157f525fe7a21fae60b4 to your computer and use it in GitHub Desktop.
Golang Is Shit E001
package main
import (
"encoding/json"
"fmt"
)
const strListOfNode = `[{"Type":1, "Cpu":1, "Mem":1},{"Type":2, "Cpu":2, "Mem":2}]`
type Node struct {
Type int
Cpu int
Mem int
}
type Resource struct {
Cpu *int
Mem *int
}
type NodeType2SpecMap map[int]*Resource
func main() {
var listOfNodes []Node
err := json.Unmarshal([]byte(strListOfNode), &listOfNodes)
if err != nil {
panic(err)
}
resMap := make(NodeType2SpecMap, 0)
// Implementation 1: Correct output {"1":{"Cpu":1,"Mem":1},"2":{"Cpu":2,"Mem":2}}
for _, rec := range listOfNodes {
if _, exists := resMap[rec.Type]; !exists {
var cpu = rec.Cpu
var mem = rec.Mem
limit := Resource{
Cpu: &cpu,
Mem: &mem,
}
resMap[rec.Type] = &limit
}
}
// print resMap
b, _ := json.Marshal(resMap)
fmt.Println(string(b))
}
package main
import (
"encoding/json"
"fmt"
)
const strListOfNode = `[{"Type":1, "Cpu":1, "Mem":1},{"Type":2, "Cpu":2, "Mem":2}]`
type Node struct {
Type int
Cpu int
Mem int
}
type Resource struct {
Cpu *int
Mem *int
}
type NodeType2SpecMap map[int]*Resource
func main() {
var listOfNodes []Node
err := json.Unmarshal([]byte(strListOfNode), &listOfNodes)
if err != nil {
panic(err)
}
resMap := make(NodeType2SpecMap, 0)
// Implementation 2: Wrong output {"1":{"Cpu":2,"Mem":2},"2":{"Cpu":2,"Mem":2}}
for _, rec := range listOfNodes {
if _, exists := resMap[rec.Type]; !exists {
resMap[rec.Type] = &Resource{
Cpu: &rec.Cpu,
Mem: &rec.Mem,
}
}
}
// print resMap
b, _ := json.Marshal(resMap)
fmt.Println(string(b))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment