- tags
- Golang
- source
- Embedding in Go: Part 3 - interfaces in structs
Interfaces are implemented as a pair of pointers, one to the underlying type and one to the underlying value. Only when both pointers are nil, the interface is nil.
var i interface{} // underlying type is nil, value is nil
fmt.Println(i == nil) // true
var x []int // value is nil
var j interface{} = x // underlying type is []int, value is nil
fmt.Println(j == nil, reflect.TypeOf(j)) // true, []int- an interface is a collection of method declarations
- a type is an interface if it implements all the methods declared in that interface
- interface can be used as data type
package main
import (
"fmt"
)
type ptr interface {
p()
}
type myint int
type mystring string
func (i myint) p() {
fmt.Printf("my int is %v\n", i)
}
func (s mystring) p() {
fmt.Printf("holy shit %s!\n", s)
}
func myprint(a ptr) {
a.p()
}
func main() {
var a myint = 1
var s mystring = "Jeck"
myprint(a)
myprint(s)
}type man struct {
name string
}
type speaker interface {
say()
}
func (m man) say() {
fmt.Printf("hi, my name is %s", m.name)
fmt.Println()
}
type fucker interface {
fuck()
}
func (m man) fuck() {
fmt.Printf("hi, my name is %s, fuck you", m.name)
fmt.Println()
}
func greet(m speaker) {
// if the underlying type also implemented fucker interface,
// call fuck() then.
if m, ok := m.(fucker); ok {
m.fuck()
return
}
m.say()
}
func main() {
x := man{name: "Bob"}
x.say()
x.fuck()
greet(x)
}see Type Switches