将参数连接成一个字符串

I have this:

if t.FieldName != "" {
        if t.FieldName != item.FieldName {
            panic(errors.New("FieldName does not match, see: ", t.FieldName, item.FieldName))
        }
}

that won't compile because errors.New takes one string arg. So I need to do something like:

panic(errors.New(joinArgs("FieldName does not match, see: ", t.FieldName, item.FieldName)))

How can I implement joinArgs, so that it concatenates all it's strings arguments into one string?

This seemed to work, not sure if it's optimal tho

func joinArgs(strangs ...string) string {
    buffer := bytes.NewBufferString("")
    for _, s := range strangs {
        buffer.WriteString(s)
    }
    return buffer.String()
}

The XY problem is asking about your attempted solution rather than your actual problem: The XY Problem. Your real problem is formatting panic error messages.


This is the normal solution to your real problem:

package main

import "fmt"

func main() {
    t := struct{ FieldName string }{FieldName: "a t.FieldName"}
    item := struct{ FieldName string }{FieldName: "an item.FieldName"}

    panic(fmt.Sprintf("FieldName does not match, see: %v %v", t.FieldName, item.FieldName))
}

Playground: https://play.golang.org/p/DaOlcqUgV_H

Output:

panic: FieldName does not match, see: a t.FieldName an item.FieldName