一分耕耘,一分收获!既然都打开这篇《根据循环内的子字符串匹配填充结构》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!
问题内容如果我们看一下下面的代码,我们如何用从字符串切片中获取的值填充结构变量? 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
我想知道出了什么问题?重构代码来解决问题的最佳方法是什么?
正确答案
希望我已经解决了这个问题,感谢 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}
}
Due to the fact that "stop:the" also wrongly matches "op:",operation
最终设置为“the”而不是“count”。现在问题似乎已经解决,strings.contains
已替换为 strings.hasprefix
。
好了,本文到此结束,带大家了解了《根据循环内的子字符串匹配填充结构》,希望本文对你有所帮助!关注编程网公众号,给大家分享更多Golang知识!