preface
Golang is in a hole. Other blogs are in a hole
The problem
- download
gopkg.in/yaml.v2
go get gopkg.in/yaml.v2
Copy the code
- use
gopkg.in/yaml.v2
Official examples:
package main
import (
"fmt"
"log"
"gopkg.in/yaml.v2"
)
var data = `
a: Easy!
b:
c: 2
d: [3, 4]
`
// Note: struct fields must be public in order for unmarshal to
// correctly populate the data.
type T struct {
A string
B struct {
RenamedC int `yaml:"c"`
D []int `yaml:",flow"`
}
}
func main() {
t := T{}
err := yaml.Unmarshal([]byte(data), &t)
iferr ! = nil { log.Fatalf("error: %v", err)
}
fmt.Printf("--- t:\n%v\n\n", t)
d, err := yaml.Marshal(&t)
iferr ! = nil { log.Fatalf("error: %v", err)
}
fmt.Printf("--- t dump:\n%s\n\n", string(d))
m := make(map[interface{}]interface{})
err = yaml.Unmarshal([]byte(data), &m)
iferr ! = nil { log.Fatalf("error: %v", err)
}
fmt.Printf("--- m:\n%v\n\n", m)
d, err = yaml.Marshal(&m)
iferr ! = nil { log.Fatalf("error: %v", err)
}
fmt.Printf("--- m dump:\n%s\n\n", string(d))
}
Copy the code
Will have problems:
go: finding module for package gopkg.in/yaml.v2
main.go:7:2: cannot find module providing package gopkg.in/yaml.v2: unrecognized import path "gopkg.in": parse https://gopkg.in/? go-get=1: no go-import meta tags ()Copy the code
The solution
Check out the official document: labix.org/gopkg.in, which states:
The actual implementation of the package is in GitHub:
https://github.com/go-yaml/yaml
Copy the code
So instead, use
go get github.com/go-yaml/yaml
Copy the code
Change the import of the official example to:
import (
"fmt"
"log"
"github.com/go-yaml/yaml"
)
Copy the code
Successful execution:
--- t:
{Easy! {2 [3 4]}}
--- t dump:
a: Easy!
b:
c: 2
d: [3, 4]
--- m:
map[a:Easy! b:map[c:2 d:[3 4]]]
--- m dump:
a: Easy!
b:
c: 2
d:
- 3
- 4
Copy the code