使用strings.Builder结合fmt.Sprintf的替代方法

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

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.Filestrings.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()

huangapple
  • 本文由 发表于 2022年12月23日 11:37:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/74895884.html
匿名

发表评论

匿名网友

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

确定