在验证后替换路径中的多个ID [Golang]

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

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
}

huangapple
  • 本文由 发表于 2022年3月10日 19:00:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/71423002.html
匿名

发表评论

匿名网友

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

确定