Created
March 9, 2014 13:40
-
-
Save kitelife/9447897 to your computer and use it in GitHub Desktop.
about interface in go
This file contains hidden or 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
| package main | |
| import ( | |
| "fmt" | |
| ) | |
| type Stringer interface { | |
| String() string | |
| } | |
| type Printer interface { | |
| Stringer // 接口嵌入。 | |
| Print() | |
| } | |
| type User struct { | |
| id int | |
| name string | |
| } | |
| func (self *User) String() string { | |
| return fmt.Sprintf("user %d, %s", self.id, self.name) | |
| } | |
| func (self *User) Print() { | |
| fmt.Println(self.String()) | |
| } | |
| func main() { | |
| var t Printer = &User{1, "Tom"} // *User 房法集包含 String、Print。 | |
| t.Print() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment