Search code examples
goslicevariadic-functions

Go cannot use name (type []string) as type string for ...string argument


i have this problem during compiling this code:

./greet.go:11:29: cannot use name (type []string) as type string in argument to CheckStringsAreUppercase

But i dont understand why. name ...string and words ...string have exactly same type. What's going on?

func Greet(name ...string) string {
        helloWord := "Hello"
    
        if CheckStringsAreUppercase(name) {
            return strings.ToUpper(helloWord)
        }
    
        return helloWord
    }
    
    func CheckStringsAreUppercase(words ...string) bool {
        for _, word := range words {
            if !CheckStringIsUppercase(word) {
                return true
            }
        }
    
        return true
    }

Solution

  • The ... notation (in a function signature) denotes a variadic parameter, which, inside that function scope is equivalent to a slice of that type, so ...string is equivalent to []string.

    When you pass N parameters into a variadic function, all of them must be assignable to the type T of the vararg.

    So by passing the parameter as CheckStringsAreUppercase(name) the type of name is effectively []string, but []string is not assignable to the type string of the variadic parameter ...string, hence your compiler error.

    The correct way to "explode" a slice into a variadic parameter is to use the three dots ... after the variable name: CheckStringsAreUppercase(name...)