Mauricio Machado
Mauricio Machado

Reputation: 643

Unexpected output in fmt.Println() function

I'm starting with golang (total noob), and I'm using a simple wrapper function for fmt.Println(str), just because it's shorter and I'm more used to it:

func echo(str ...interface{}) {
  fmt.Println(str)
}

The thing is that the output for echo("Hello") is [Hello] instead of Hello.

Am I missing some syntax detail here? How can I change the function to work as expected?

Besides the actual need for this function, I'm interested in the language-specific details about this issue.

Thanks!

Upvotes: 0

Views: 171

Answers (1)

Maxian Nicu
Maxian Nicu

Reputation: 2294

The problem is that you send to fmt.Println parameter as a slice, but not as varadic.

Change your method to :

func echo(str ...interface{}) {
    fmt.Println(str...)
}

And it will work as you expect.

Check topic Arguments to variadic functions from this site.

Upvotes: 2

Related Questions