go 结构体继承,及其方法

2022/3/19 6:29:52

本文主要是介绍go 结构体继承,及其方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

package main

import (
	"fmt"
)


type Animal struct {
	Name string  
	Sex string
}


func (a *Animal)Talk(){
	fmt.Printf("Animal is talk, i'm %s\n", a.Name)
}
func (a *Animal)Eat(){
	fmt.Println("dog Animal is eat")
}


type PuruAnimal  struct{}

type Dog  struct{
	Feet string
	//Animal         // 值类型
	*Animal          // 指针类型
	*PuruAnimal      // 指针类型
}


func (p *PuruAnimal)Talk(){
	fmt.Println("puru dongwu is talking\n")
}

func (p *PuruAnimal)Walk(){
	fmt.Println("puru dongwu is walking\n")
}


func (d *Dog)Talk(){
	fmt.Printf("dog %s is talking\n",d.Name)
}


func (d *Dog)Eat(){
	fmt.Printf("dog %s is eat\n",d.Name)
}


func main(){
	var d *Dog = &Dog{
		Feet:"four feet",
		Animal:&Animal{
			Name:"旺财",
			Sex:"公",
		},
		PuruAnimal:&PuruAnimal{},
	}

	d.Eat()
	d.Talk()
	d.Name = "小黑"
	d.Sex ="公"
	d.Eat()
	d.Talk()

	d.Animal.Talk()
	d.PuruAnimal.Talk()
	d.Talk()
	d.Walk()
}

输出:

dog 旺财 is eat
dog 旺财 is talking
dog 小黑 is eat
dog 小黑 is talking
Animal is talk, i'm 小黑
puru dongwu is talking

dog 小黑 is talking
puru dongwu is walking


这篇关于go 结构体继承,及其方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程