根据循环中的子字符串匹配填充结构

Filling a struct based on substring matches within a loop

提问人:sci9 提问时间:2/18/2023 最后编辑:Robsci9 更新时间:2/19/2023 访问量:97

问:

如果我们看一下下面的代码,我们如何用从字符串切片中获取的值来填充结构变量?https://go.dev/play/p/KkcPzr5r28w

package main

import (
    "fmt"
    "os"
    "strings"
)

type Config struct {
    Operation string
    Stop      string
    Start     string
    File      string
}

func ParseConfig(list []string) Config {

    var c Config
    for _, elem := range list {
        if strings.Contains(elem, "op:") {
            subList := strings.SplitAfterN(elem, ":", 2)
            c.Operation = subList[1]
        } else if strings.Contains(elem, "stop:") {
            subList := strings.SplitAfterN(elem, ":", 2)
            c.Stop = subList[1]
        } else if strings.Contains(elem, "start:") {
            subList := strings.SplitAfterN(elem, ":", 2)
            c.Start = subList[1]
        } else if strings.Contains(elem, "file:") {
            subList := strings.SplitAfterN(elem, ":", 2)
            c.File = subList[1]
        }
    }
    return c
}

func main() {

    c := ParseConfig(os.Args[1:])
    fmt.Println(c) // {count the  quick /tmp/file1.txt}
}

使用以下参数调用时,此程序不会返回正确的响应:

go run scan.go op:count start:quick stop:the file:/tmp/file1.txt

我想知道怎么了?重构代码以解决问题的最佳方法是什么?

string go 结构 体切片

评论


答:

0赞 sci9 2/19/2023 #1

希望我已经修复了它,感谢 Gophers 的社区:https://go.dev/play/p/u_Dc7ctbsib

package main

import (
    "fmt"
    "strings"
)

type Config struct {
    Operation string
    Stop      string
    Start     string
    File      string
}

func main() {
    list := []string{"op:count", "start:quick", "stop:the", "file:/tmp/file1.txt"}
    fmt.Println(list)
    var c Config
    for _, v := range list {
        if strings.HasPrefix(v, "op:") {
            subList := strings.SplitAfterN(v, ":", 2)
            c.Operation = subList[1]
        } else if strings.Contains(v, "stop:") {
            subList := strings.SplitAfterN(v, ":", 2)
            c.Stop = subList[1]
        } else if strings.Contains(v, "start:") {
            subList := strings.SplitAfterN(v, ":", 2)
            c.Start = subList[1]
        } else if strings.Contains(v, "file:") {
            subList := strings.SplitAfterN(v, ":", 2)
            c.File = subList[1]
        }
    }
    fmt.Println(c) // {count the  quick /tmp/file1.txt}

}



由于“stop:the”也错误地匹配了“op:”,因此最终设置为“the”而不是“count”。现在问题似乎解决了,它被替换为 .Operationstrings.Containsstrings.HasPrefix