go interface - ghdrako/doc_snipets GitHub Wiki

Go provides a type called an interface that stores any value that declares a set of methods. The implementing value must have declared this set of methods to implement the interface. The value may also have other methods besides the set declared in the interface type.

Defining an interface type

type Stringer interface {
String() string
}

Note Stringer is a real type defined in the standard library's fmt package. Types that implement Stringer will have their String() method called when passed to print functions in the fmt package. Don't let the similar names confuse you; Stringer is the interface type's name, and it defines a method called String() (which is uppercase to distinguish it from the string type, which is lowercase). That method returns a string type that should provide some human-readable representation of your data.

type StrList []string
func (s StrList) String() string {
return strings.Join(s, ",")
}

func main() {
  var nameList Stringer = StrList{"David", "Sarah"}
  PrintStringer(nameList) // Prints: David,Sarah
}


The blank interface – Go's universal value

interface{} is Go's universal value container that can be used to pass any value to a function and then figure out what it is and what to do with it later.

var i interface{}
i = 3
i = "hello world"
i = 3.4
i = Person{First: "John"}

This is all legal because each of those values has types that define all the methods that the interface defined (which were no methods). This allows us to pass around values in a universal container. This is actually how fmt.Printf() and fmt.Println() work.

Note about interface{} in 1.18: Go 1.18 has introduced an alias for the blank interface{}, called any. The Go standard library now uses any in place of interface{}. However, all packages prior to 1.18 will still use interface{}. Both are equivalent and can be used interchangeably.