如何在Golang中解析参数列表(多个重复且以逗号分隔的参数)?

huangapple go评论100阅读模式
英文:

How to parse a list of parameters in Golang (multiple duplicate and comma separated)?

问题

我需要解析GO中的不同参数(多个重复且以逗号分隔)。我该如何处理以下示例:

go run ./test.go -param "one, two" -param "tree" -param "four"

这个示例很好,但对于上述示例不起作用:

[one, two tree four]

也就是说,它可以处理多个重复参数,但无法处理逗号分隔的参数。

我该如何改进上述脚本以解析多个参数,包括逗号分隔的参数,以获得以下结果(无逗号):

[one two tree four]

英文:

I need to parse different parameters in GO (multiple duplicate and comma separated). How can I do it for this example:

go run ./test.go -param "one, two" -param "tree" -param "four"

This example is good but doesn't work for the mentioned example:

[one, two tree four]

I.e. it works for the multiple duplicate parameters but doesn't work for the comma separated.

How can I improve the mentioned script to parse several parameters including comma separated to get this (no comma) in the result:

[one two tree four]

?

答案1

得分: 2

修改Set方法,使其在逗号处分割参数,并将结果追加到接收器中。

func (i *arrayFlags) Set(value string) error {
    s := strings.Split(value, ",")
    for i := range s {
        s[i] = strings.TrimSpace(s[i])
    }
    *i = append(*i, s...)
    return nil
}
英文:

Modify the Set method such that it splits its argument at comma and appends the result to the receiver.

func (i *arrayFlags) Set(value string) error {
    s := strings.Split(value, ",")
    for i := range s {
        s[i] = strings.TrimSpace(s[i])
    }
	*i = append(*i, s...)
	return nil
}

huangapple
  • 本文由 发表于 2021年7月8日 18:48:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/68300180.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定