如何在Golang中正确使用可变参数args?

I am complete beginner with Go and I am trying to pass variadic args to encodeit method as a string that will hash the string, otherwise pass an empty string. I wan't to print out hashed string.

I have tried multiple things, but could not get it to work.

package main

import(
    "crypto/sha512"
    "encoding/hex"
    "fmt"
)

func encodeit(content string) string {
    sha_512 := sha512.New()
    sha_512.Write([]byte(content))
    contentH := sha_512.Sum(nil)
    contentHash := hex.EncodeToString([]byte(contentH))
    return contentHash
}

func some(payload ...string) {
    if len(payload) == 1 {
        contentHash := encodeit(payload)
    } else {
        contentHash := encodeit("")
    }
    return contentHash
}

func main() {
    fmt.Println(some(`{"stockSymbol": "TSLA"}`))
}

Here is the error log

# command-line-arguments
.\stackOverflow.go:19:26: cannot use payload (type []string) as type string in argument to encodeit
.\stackOverflow.go:23:2: too many arguments to return
.\stackOverflow.go:23:9: undefined: contentHash
.\stackOverflow.go:27:18: some("{\"stockSymbol\": \"TSLA\"}") used as value

check your func return value:

func some(payload ...string) string

you missed the return type string.

payload becomes an array of strings ([]string) when using an ellipsis (...). It can be iterated on using a key,value for loop:

func printEncoded(payload ...string) {
    for i, value := range payload {
        fmt.Println(i, encode(value))
    }
}

Use printEncoded("TSLA","AMD","DOW") and you won't have to create your own []string array as an argument ([]string{"TSLA","AMD","DOW"}).

You're also going to want to take a look at the JSON package for parsing: {"stockSymbol": "TSLA"}

Fixed Playground