Last active
November 5, 2019 09:40
-
-
Save kjk/07b87878ae9efeb2478a52f437a33d40 to your computer and use it in GitHub Desktop.
Interfaces
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
// :collection Essential Go | |
package main | |
import ( | |
"fmt" | |
"strconv" | |
) | |
// :show start | |
// Stringer is an interface with a single method | |
type Stringer interface { | |
String() string | |
} | |
// User struct that implements Stringer interface | |
type User struct { | |
Name string | |
} | |
func (u *User) String() string { | |
return u.Name | |
} | |
// Any type can implement an interface. Here we create | |
// an alias of int type an implement Stringer interface | |
type MyInt int | |
func (mi MyInt) String() string { | |
return strconv.Itoa(int(mi)) | |
} | |
// printTypeAndString accepts an interface. 's' can be any value | |
// that implements Stringer interface | |
func printTypeAndString(s Stringer) { | |
fmt.Printf("%T: %s\n", s, s) | |
} | |
func main() { | |
u := &User{Name: "John"} | |
printTypeAndString(u) | |
n := MyInt(5) | |
printTypeAndString(n) | |
} | |
// :show end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment