英文:
Replace multiple ids in a path after validation [Golang]
问题
我有一个由/
分隔的路径,并且希望用一个常量值替换多个id。我遇到的问题是,一旦验证了第一个id,它就进行替换并停止了。我猜想在Golang中应该有一种类似于do while的结构(参见这个资源 - 我知道Go中没有这样的结构),我尝试使用了以下代码:
for true {
// 做一些事情
}
但仍然只有第一个id被替换了。有什么想法吗?谢谢。
这是我在Go Playground上的示例,包含原始实现。
英文:
I have a path delimited by /
and an expectation to have multiple ids I want to replace with a constant value. The issue I am facing is that once it validates the first id, it performs the replacement and stops. My assumption is that I should be having some sort of do while in Golang (see this resource - I know there is no such a construct in Go) and I have attempted at using:
for true {
// do something
}
but still only the first id is replaced. Any idea? Thank you
Here is my Go Playground example with the original implementation
答案1
得分: 2
问题是你在第一次匹配后就提前使用了 return
。由于你正在迭代路径的部分,你应该将 strings.Replace()
的结果赋给一个变量,并在循环结束后返回。将结果赋给 path
而不是返回它,这样就可以按预期工作了。
func SubstituteById(path string, repl string) string {
ids := strings.Split(path, "/")
for _, id := range ids {
if fastuuid.ValidHex128(id) {
path = strings.Replace(path, id, repl, -1)
}
}
return path
}
英文:
The problem is you early return
after first match. Since you iterating parts of path you should assign result of strings.Replace()
to a variable and return after for loop. Assign to path
instead of returning and it should work as expected.
func SubstituteById(path string, repl string) string {
ids := strings.Split(path, "/")
for _, id := range ids {
if fastuuid.ValidHex128(id) {
path = strings.Replace(path, id, repl, -1)
}
}
return path
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论