接口的实现
- package main
- import "fmt"
- type Animal interface {
- // 出生
- SayHelloWord()
- // 死亡
- Godie()
- // 生活
- Live(food string) (Energy int)
- }
- type Pig struct {
- Name string
- }
- /* 猪的指针实现了动物接口 */
- // 出生
- func (p *Pig)SayHelloWord(){
- fmt.Printf("%s 哼哼哼 \ n",p.Name)
- }
- // 死亡
- func (p *Pig)Godie(){
- fmt.Printf("%s 啊啊啊我死了 \ n",p.Name)
- }
- // 生活
- func (p *Pig)Live(food string) (Energy int){
- fmt.Printf("%s 食用了一些 %s, 生产了 %d 卡路里 \ n",p.Name,food,1200)
- return 1200
- }
- type Cat struct {
- Name string
- }
- /* 猫的指针实现了动物接口 */
- // 出生
- func (c *Cat)SayHelloWord(){
- fmt.Printf("%s 出生了 \ n",c.Name)
- }
- // 死亡
- func (c *Cat)Godie(){
- fmt.Printf("%s: 糟了 life-=1\n",c.Name)
- }
- // 生活
- func (c *Cat)Live(food string)(Energy int){
- fmt.Printf("铲屎官给 %s 大人服用了一些 %s\n",c.Name,food)
- return 1
- }
- func main031() {
- var animal Animal
- /* 一个动物实例, 既可以指向一只猪的指针, 又可以指向一只猫的指针 */
- //animal = &Pig{"佩奇"}
- animal = &Cat{"加菲"}
- /* 无视当前的 animal 的具体类型, 调度其动物的共性 */
- animal.SayHelloWord()
- animal.Godie()
- animal.Live("饲料")
- }
- /* 开一个肉联厂 */
- func main() {
- animals := make([]Animal, 0)
- animals = append(animals, &Pig{"佩奇"})
- animals = append(animals, &Cat{"加菲"})
- for _,animal := range animals{
- animal.Live("饲料")
- animal.Godie()
- }
- }
接口的类型断言
- package main
- import "fmt"
- type Animal interface {
- // 出生
- SayHelloWord()
- // 死亡
- Godie()
- // 生活
- Live(food string) (Energy int)
- }
- type Pig struct {
- Name string
- }
- /* 猪的指针实现了动物接口 */
- // 出生
- func (p *Pig)SayHelloWord(){
- fmt.Printf("%s 哼哼哼 \ n",p.Name)
- }
- // 死亡
- func (p *Pig)Godie(){
- fmt.Printf("%s 啊啊啊我死了 \ n",p.Name)
- }
- // 生活
- func (p *Pig)Live(food string) (Energy int){
- fmt.Printf("%s 食用了一些 %s, 生产了 %d 卡路里 \ n",p.Name,food,1200)
- return 1200
- }
- type Cat struct {
- Name string
- }
- /* 猫的指针实现了动物接口 */
- // 出生
- func (c *Cat)SayHelloWord(){
- fmt.Printf("%s 出生了 \ n",c.Name)
- }
- // 死亡
- func (c *Cat)Godie(){
- fmt.Printf("%s: 糟了 life-=1\n",c.Name)
- }
- // 生活
- func (c *Cat)Live(food string)(Energy int){
- fmt.Printf("铲屎官给 %s 大人服用了一些 %s\n",c.Name,food)
- return 1
- }
- func main031() {
- var animal Animal
- /* 一个动物实例, 既可以指向一只猪的指针, 又可以指向一只猫的指针 */
- //animal = &Pig{"佩奇"}
- animal = &Cat{"加菲"}
- /* 无视当前的 animal 的具体类型, 调度其动物的共性 */
- animal.SayHelloWord()
- animal.Godie()
- animal.Live("饲料")
- }
- /* 开一个肉联厂 */
- func main() {
- animals := make([]Animal, 0)
- animals = append(animals, &Pig{"佩奇"})
- animals = append(animals, &Cat{"加菲"})
- for _,animal := range animals{
- animal.Live("饲料")
- animal.Godie()
- }
- }
来源: http://www.bubuko.com/infodetail-3296957.html