Skip to content

Instantly share code, notes, and snippets.

@0xrgb
Last active July 18, 2018 22:39
Show Gist options
  • Save 0xrgb/82014828ad97c42898fff647d0fa81ca to your computer and use it in GitHub Desktop.
Save 0xrgb/82014828ad97c42898fff647d0fa81ca to your computer and use it in GitHub Desktop.
Method set and nil interface
// https://stackoverflow.com/questions/41922181/go-why-implicit-non-pointer-methods-not-satisfy-interface
// https://golang.org/doc/faq#different_method_sets
// https://golang.org/doc/faq#nil_error
package main
import "fmt"
type user struct {
id int
name string
}
func (u *user) String() string {
return fmt.Sprint("ID: ", u.id, ", Name: ", u.name)
}
func main() {
var x = user{name: "John", id: 1}
var y = &user{name: "Jim", id: 2}
//var xs fmt.Stringer = x
var ys fmt.Stringer = y
var zs fmt.Stringer
var ws fmt.Stringer = (*user)(nil)
if ws != nil {
fmt.Println(x) // {1 John}
fmt.Println(x.String()) // ID: 1 / Name: John
fmt.Println(y) // ID: 2 / Name: Jim
fmt.Println(ys) // ID: 2 / Name: Jim
fmt.Println(zs) // <nil>
fmt.Println(ws) // <nil>
_ = zs.String() // panic
_ = ws.String() // panic in String()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment