2

I read about the interfaces a lot and I think I understand how it works. I read about the interface{} type and use it to take an argument of function. It is clear. My question (and what I don't understand) is what is my benefit if I am using it. It is possible I didn't get it entirely but for example I have this:

package main

import (
    "fmt"
)

func PrintAll(vals []interface{}) {
    for _, val := range vals {
        fmt.Println(val)
    }
}

func main() {
    names := []string{"stanley", "david", "oscar"}
    vals := make([]interface{}, len(names))
    for i, v := range names {
        vals[i] = v
    }
    PrintAll(vals)
}

Why is it better than this:

package main

import (
    "fmt"
)

func PrintAll(vals []string) {
    for _, val := range vals {
        fmt.Println(val)
    }
}

func main() {
    names := []string{"stanley", "david", "oscar"}
    PrintAll(names)
}
icza
  • 389,944
  • 63
  • 907
  • 827
PumpkinSeed
  • 2,945
  • 9
  • 36
  • 62
  • Use an interface when you may way to change out the underlying implementation, but not change all the code that uses it. – Carcigenicate Oct 25 '16 at 11:44
  • What is the benefit of using an interface? Decouple code. See https://stackoverflow.com/a/62297796/12817546. Call a method “dynamically”. See https://stackoverflow.com/a/62336440/12817546. Access a Go package. See https://stackoverflow.com/a/62278078/12817546. Assign any value to a variable. See https://stackoverflow.com/a/62337836/12817546. –  Jul 10 '20 at 09:44

1 Answers1

1

If you're always want to print string values, then the first using []interface{} is not better at all, it's worse as you lose some compile-time checking: it won't warn you if you pass a slice which contains values other than strings.

If you want to print values other than strings, then the second with []string wouldn't even compile.

For example the first also handles this:

PrintAll([]interface{}{"one", 2, 3.3})

While the 2nd would give you a compile-time error:

cannot use []interface {} literal (type []interface {}) as type []string in argument to PrintAll

The 2nd gives you compile-time guarantee that only a slice of type []string is passed; should you attempt to pass anything other will result in compile-time error.

Also see related question: Why are interfaces needed in Golang?

Community
  • 1
  • 1
icza
  • 389,944
  • 63
  • 907
  • 827
  • Thank you. Can you please say a brief real world example? It is okay, just I can't imagine how can I use the interface{} benefits in a real world problem. – PumpkinSeed Oct 25 '16 at 12:02
  • @PumpkinSeed [`fmt.Println()`](https://golang.org/pkg/fmt/#Println) which you call in your example also takes values of `interface{}` type, which means you can pass any value to it. – icza Oct 25 '16 at 12:05