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

时间:2017-11-19 20:56:03

标签: go

我试图解析日志字符串,其中字段与" |"焦炭。所有日志都假设有20个字段,但有些日志较少。我不想丢弃它们,而是用日志字符串中的任何信息填充val l = "[" :: List("mapped_string1", "mapped_string2") .flatMap(s => List(", ", s)) .tail ::: List("]") println(implicitly[Mapper[List[String], String]].map(l)) //[mapped_string1, mapped_string2]

Log{}

知道无法检查切片中是否存在索引,这看起来不是最理想的:

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

有没有更好的方法呢?

由于

2 个答案:

答案 0 :(得分:5)

一种选择是将switchfallthrough

一起使用
switch len(fields) {
case 20:
    log.Field20 = something(fields[19])
    fallthrough

// ...

case 3:
   log.Field3 = fields[2]
   fallthrough
case 2:
    log.Field2, _ = strconv.ParseUint(fields[1], 0, 64)
    fallthrough
case 1:
    log.Field1 = fields[0]
}

playground example(谢谢@mkopriva的首例)

答案 1 :(得分:1)

一种可能性是简单地确保切片中始终有20个元素。假设您使用fields填充strings.Split,例如:

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],
}