Created
May 19, 2023 02:14
-
-
Save aichaoxy/fe85a3e9729e157f525fe7a21fae60b4 to your computer and use it in GitHub Desktop.
Golang Is Shit E001
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
https://github.com/xxpxxxxp/intellij-plugin-golangci-lint/blob/master/explanation/exportloopref.md