Formatted errors.New

前端 未结 1 1416
伪装坚强ぢ
伪装坚强ぢ 2021-01-17 23:28

I would like to implement a version of errors.New that accepts the same parameters as fmt.Sprintf To do so I wrote the following function:

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-17 23:40

    fmt.Errorf already does what you are trying to do. Looking at its source, you can see what went wrong:

    // Errorf formats according to a format specifier and returns the string
    // as a value that satisfies error.
    func Errorf(format string, a ...interface{}) error {
            return errors.New(Sprintf(format, a...))
    }
    

    Note your code is missing the ... after a. From the spec:

    Passing arguments to ... parameters

    If the final argument is assignable to a slice type []T, it may be passed unchanged as the value for a ...T parameter if the argument is followed by .... In this case no new slice is created.

    Given the slice s and call

    s := []string{"James", "Jasmine"}
    Greeting("goodbye:", s...)
    

    within Greeting, who will have the same value as s with the same underlying array.

    0 讨论(0)
提交回复
热议问题