英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论