I got "need type assertion" error when trying to convert interface {} array to string array.
Having looked at the following two answers,
I'm still can't get my special case working -- I'm Unmarshaling the following yaml into a `map[interface{}]interface{}` structure:
const data = `
Colors:
- red
- blue
- white
`
m := make(map[interface{}]interface{})
err := yaml.Unmarshal([]byte(data), &m)
The unmarshalled data is apparently some kind of string array. How can tell Go to treat them so?
The code is kind of long, but I've got the part up to "fmt.Println("\nNext")" working. It is the next two lines I'm struggling to get working.
Please help.
package main
import (
"fmt"
"os"
"strings"
"text/template"
"gopkg.in/yaml.v2"
)
const data = `
Colors:
- red
- blue
- white
`
const templ1 = `{{range .Colors}}{{.}}, {{end}}`
const templ2 = `{{join .Colors}}`
func main() {
m := make(map[interface{}]interface{})
err := yaml.Unmarshal([]byte(data), &m)
checkError(err)
fmt.Printf("--- m:\n%v\n\n", m)
d, err := yaml.Marshal(&m)
checkError(err)
fmt.Printf("--- m dump:\n%s\n\n", string(d))
t := template.New("Test template")
t, err = t.Parse(templ1)
checkError(err)
err = t.Execute(os.Stdout, m)
checkError(err)
colors := []string{"red", "white", "blue"}
t = template.Must(template.New("").Funcs(funcs).Parse(templ2))
err = t.Execute(os.Stdout, struct{ Colors []string }{colors})
checkError(err)
fmt.Println("\nNext")
fmt.Println(strings.Join(m["Colors"].([]string), ", "))
err = t.Execute(os.Stdout, struct{ Colors []string }{m["Colors"].([]string)})
checkError(err)
}
var funcs = template.FuncMap{
"join": func(s []string) string { return strings.Join(s, ", ") },
}
func checkError(err error) {
if err != nil {
fmt.Println("Fatal error ", err.Error())
os.Exit(1)
}
}