golang的继承

golang中并没有继承以及oop,但是我们可以通过struct嵌套来完成这个操作。

  1. 定义struct
    以下定义了一个Person结构体,这个结构体有Eat方法以及三个属性
type Person struct {
    
    
	Name  string
	Age   uint16
	Phone string
}

func (recv *Person) Eat() {
    
    
	fmt.Printf("recv.Name: %v 正在吃饭\n", recv.Name)
}
  1. 定义嵌套struct
type Chinese struct {
    
    
	Person
	DangYuan bool
}

func (recv *Chinese) Jubao() {
    
    
	if recv.DangYuan == true {
    
    
		fmt.Printf("\"你可以举报\": %v\n", "你可以举报")
	} else {
    
    
		fmt.Printf("\"你不可以举报\": %v\n", "你不可以举报")
	}
}

如上,Chinese嵌套了Person,所以Chinese也有Person的属性,以及方法
3. main.go

package main

import "fmt"

type Person struct {
    
    
	Name  string
	Age   uint16
	Phone string
}

func (recv *Person) Eat() {
    
    
	fmt.Printf("recv.Name: %v 正在吃饭\n", recv.Name)
}

type Chinese struct {
    
    
	Person
	DangYuan bool
}

func (recv *Chinese) Jubao() {
    
    
	if recv.DangYuan == true {
    
    
		fmt.Printf("\"你可以举报\": %v\n", "你可以举报")
	} else {
    
    
		fmt.Printf("\"你不可以举报\": %v\n", "你不可以举报")
	}
}

func main() {
    
    
	chinese := Chinese{
    
    Person{
    
    Age: 100, Name: "ellis", Phone: "123456789"}, true}
	chinese.Eat()
	chinese.Jubao()
}

猜你喜欢

转载自blog.csdn.net/weixin_43632687/article/details/132446310