dsiuy42084 2017-11-19 20:56
浏览 40
已采纳

如何使用可变数量的项目转换[] string?

I'm trying to parse log strings, where fields are glued with "|" char. All logs suppose to have 20 fields, but some logs have less. I don't want to discard them, but rather fill Log{} with whatever info was there in the log string.

type Log struct {
     Field1  string
     Field2  uint64
     Field3  string
     // ...
     Field20 string
}

Knowing that it's not possible to check if index exists within a slice, this looks suboptimal:

log := Log{}
c := len(fields)

if c > 0 {
    log.Field1 = fields[0]
}

if c > 1 {
    log.Field2, _ = strconv.ParseUint(fields[1], 0, 64)
}

if c > 3 {
    log.Field3 = fields[2]
}

//...

Any better ways doing this?

Thanks

  • 写回答

2条回答 默认 最新

  • duanfu3634 2017-11-20 11:53
    关注

    One possibility would be to simply ensure that you always have 20 elements in your slice. Assuming you're populating fields with strings.Split, for example:

    fields := make([]string, 20)
    copy(fields, strings.Split(input, ","))
    
    // Now `fields` has 20 elements, the first N of which are populated
    // by your input, the remainder of which are empty strings (""), so
    // you can easily set your struct fields now.
    
    log := Log{
        Field1:  fields[0],
        Field2:  fields[1],
        // ...
        Field20: fields[19],
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案