Home > Enterprise >  Alternative to using strings.Builder in conjunction with fmt.Sprintf
Alternative to using strings.Builder in conjunction with fmt.Sprintf

Time:12-23

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?

CodePudding user response:

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()
  •  Tags:  
  • go
  • Related