英文:
Alternative to using strings.Builder in conjunction with fmt.Sprintf
问题
我正在学习Go语言中的strings
包,并尝试构建一个简单的错误消息。
我了解到strings.Builder
是一种非常高效的字符串连接方式,而fmt.Sprintf
则可以进行字符串插值。
说到这里,我想了解最佳的字符串连接方式。例如,这是我创建的代码:
func generateValidationErrorMessage(err error) string {
errors := []string{}
for _, err := range err.(validator.ValidationErrors) {
var b strings.Builder
b.WriteString(fmt.Sprintf("[%s] failed validation [%s]", err.Field(), err.ActualTag()))
if err.Param() != "" {
b.WriteString(fmt.Sprintf("[%s]", err.Param()))
}
errors = append(errors, b.String())
}
return strings.Join(errors, "; ")
}
还有其他更好的方法吗?使用s1 + s2
被认为更差吗?
英文:
I am learning about the strings
package in Go and I am trying to build up a simple error message.
I read that strings.Builder
is a very eficient way to join strings, and that fmt.Sprintf
lets me do some string interpolation.
With that said, I want to understand the best way to join a lot of strings together. For example here is what I create:
func generateValidationErrorMessage(err error) string {
errors := []string{}
for _, err := range err.(validator.ValidationErrors) {
var b strings.Builder
b.WriteString(fmt.Sprintf("[%s] failed validation [%s]", err.Field(), err.ActualTag()))
if err.Param() != "" {
b.WriteString(fmt.Sprintf("[%s]", err.Param()))
}
errors = append(errors, b.String())
}
return strings.Join(errors, "; ")
}
Is there another/better way to do this? Is using s1 + s2
considered worse?
答案1
得分: 2
你可以使用fmt
直接将内容打印到strings.Builder
中。使用fmt.Fprintf(&builder, "格式字符串", args)
。
以Fprint...
开头的fmt
函数,表示"文件打印",允许你将内容打印到io.Writer
,比如os.File
或strings.Builder
。
此外,不需要使用多个builder
并在最后将它们的字符串连接起来,只需使用一个单独的builder
并不断向其中写入内容。如果你想要添加分隔符,可以在循环内轻松实现:
var builder strings.Builder
for i, v := range values {
if i > 0 {
// 除非是第一项,否则在其前面添加分隔符。
fmt.Fprint(&builder, "; ")
}
fmt.Fprintf(&builder, "一些格式 %v", v)
}
var output = builder.String()
英文:
You can use fmt
to print directly to the strings.Builder
. Use fmt.Fprintf(&builder, "format string", args)
.
The fmt
functions beginning with Fprint...
, meaning "file print", allow you to print to an io.Writer
such as a os.File
or strings.Builder
.
Also, rather than using multiple builders and joining all their strings at the end, just use a single builder and keep writing to it. If you want to add a separator, you can do so easily within the loop:
var builder strings.Builder
for i, v := range values {
if i > 0 {
// unless this is the first item, add the separator before it.
fmt.Fprint(&builder, "; ")
}
fmt.Fprintf(&builder, "some format %v", v)
}
var output = builder.String()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论