Last active
July 18, 2018 22:39
-
-
Save 0xrgb/82014828ad97c42898fff647d0fa81ca to your computer and use it in GitHub Desktop.
Method set and nil interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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