2016-09-24 20:02
浏览 124


I'm attempting to read a YAML file using GO and mapping it to a structure that I've defined. The YAML is below:

--- # go_time_tracker.yml
owner: "Phillip Dudley"
initialized: "2012-10-31 15:50:13.793654 +0000 UTC"
  - action: "start"
    time: "2012-10-31 15:50:13.793654 +0000 UTC"
  - action: "stop"
time: "2012-10-31 16:00:00.000000 +0000 UTC"

I used the following code to read in the file, Unmarshal the data, and then print some of the data.

package main

import (

type Date_File struct {
    Owner    string      `yaml:"owner"`
    Init     time.Time   `yaml:"initialized"`
    TimeData []Time_Data `yaml:"time_data"`

type Time_Data struct {
    Action string    `yaml:"action"`
    Time   time.Time `yaml:"time"`

func checkerr(err error) {
    if err != nil {

func read() (td *Date_File) {
    //td := &Date_File{}
    gtt_config, err := ioutil.ReadFile("go_time_tracker.yml")
    err = yaml.Unmarshal(gtt_config, &td)
    return td

func main() {
    time_data := read()

When I run this, the first fmt.Println(time_data) works, showing the reference and its data. The next line though fails saying that the index is out of range. This is the error:

$ go run yaml_practice_2.go 
&{Phillip Dudley 0001-01-01 00:00:00 +0000 UTC []}
panic: runtime error: index out of range

goroutine 1 [running]:
panic(0x559840, 0xc82000a0e0)
    /usr/lib/go-1.6/src/runtime/panic.go:481 +0x3e6
    /home/predatorian/Documents/go/src/predatorian/yaml/yaml_practice_2.go:41 +0x2aa
exit status 2

I then thought maybe my YAML wasn't formatted properly, so I loaded the YAML file into Ruby's IRB, and this is what I got.

irb(main):004:0> data2 = YAML.load("go_time_tracker.yml"))
=> {"owner"=>"Phillip Dudley", "initialized"=>"2012-10-31 15:50:13.793654 +0000 UTC", "time_data"=>[{"action"=>"start", "time"=>"2012-10-31 15:50:13.793654 +0000 UTC"}, {"action"=>"stop", "time"=>"2012-10-31 16:00:00.000000 +0000 UTC"}]}

The IRB output shows that my YAML is formatted properly, however, I don't think I'm Unmarshalling it properly then. However, I'm not sure what I would need to do to get this to work. I'm sure I'm not thinking of how to do this properly since Ruby hides a lot of it.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题