2016-02-21 04:42



I am trying to read a string of data from a csv file and parse the data into a list of custom objects. The main issue that I am having is converting the data to the correct datatype within the loop.

Here is my custom object:

type yahooInfoObj struct {
    date time.Time
    open float32
    high float32
    low float32
    close float32
    volume int
    adjClose float32

Here is my function that gets the data and attempts to parse it:

func getSingleCompanyData(search searchObj) []yahooInfoObj {
    searchQuery := buildYahooFinanceDataQueryString(search)
    data := getRequest(searchQuery)

    r := csv.NewReader(strings.NewReader(data))
    var stats []yahooInfoObj

    // Read csv file
    result, _ := r.ReadAll()

    //loop through each returned stat (line)
    for i := range result {
        //skip the first entry due to column names being returned
        if i != 0{
            stat := result[i]
            stats = append(stats, yahooInfoObj{stat[0],strconv.ParseFloat(stat[1],32),strconv.ParseFloat(stat[2],32),strconv.ParseFloat(stat[3],32),strconv.ParseFloat(stat[4],32),strconv.Atoi(stat[5]),strconv.ParseFloat(stat[6],32)})

    return stats

Here is some sample data of which would be returned and placed in the data variable:

Date,Open,High,Low,Close,Volume,Adj Close

I am new to the go language and would really appreciate any advice. Thanks in advance!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • duanjiaolia97750 duanjiaolia97750 5年前

    There's a few things that I notice right off the bat:

    • You're not using a time.Time object to send to your yahooInfoObj struct. You're sending a string

    • You're calling functions that return multiple values in a "single value context". This means that you are just expecting to ignore the second value, but to Go this is an error in your coding. You'll have to explicitly set these values.

    • You're not checking multiple errors. Always check errors - it'll prevent "gotchas" in the future.

    It's not perfect, but here's a seemingly working playground:

    点赞 评论 复制链接分享