编程 Go的父子类的简单使用

2024-11-18 14:56:32 +0800 CST views 879

Go的父子类的简单使用

简介

在Go语言中,父子类的概念类似于面向对象编程中的基类和扩展类。父类通常定义一些通用的功能,而子类则在此基础上进行功能的扩展。Go的这种实现方式有些类似于抽象类及其子类的具体实现。

代码示例

下面是一个简单的代码示例,展示了如何在Go中实现类似于父子类的结构:

package parentchildclass

import "fmt"

// 定义一个接口
type WriteInterface interface {
    Write()
}

// 定义父类
type WriteParent struct {
    name string
}

// 父类中的方法
func (w *WriteParent) Write() {
    fmt.Println("parent")
}

// 父类中的数据校验方法,可以考虑基于泛型或者抽象接口来实现
func (w *WriteParent) CheckData() {
    fmt.Println("check data")
}

// 定义子类,继承自父类
type Child struct {
    *WriteParent
}

// 子类覆盖父类的方法
func (c *Child) Write() {
    c.CheckData()
    fmt.Println("child")
}

测试用例

下面是一个简单的测试用例,用来测试子类的 Write 方法:

package parentchildclass

import "testing"

func TestChild_Write(t *testing.T) {
    child := &Child{&WriteParent{}}
    child.Write()
}

输出结果

=== RUN   TestChild_Write
check data
child
--- PASS: TestChild_Write (0.00s)
PASS

总结

从上述代码可以看到,子类 Child 覆盖了父类 WriteParentWrite 方法。在这种用法中,可以在父类中定义好公共方法(类似于抽象方法)和一些非抽象的公共方法(主要用于数据的校验和处理等逻辑),而子类则可以自定义实现这些公共方法,并调用父类的非抽象方法进行数据校验或逻辑处理。

这也可以看作是Go语言中实现父子类(或基类与子类)的一种典型应用方式。

复制全文 生成海报 编程 Go语言 面向对象

推荐文章

Python 获取网络时间和本地时间
2024-11-18 21:53:35 +0800 CST
Vue3中的Slots有哪些变化?
2024-11-18 16:34:49 +0800 CST
php获取当前域名
2024-11-18 00:12:48 +0800 CST
一个简单的打字机效果的实现
2024-11-19 04:47:27 +0800 CST
避免 Go 语言中的接口污染
2024-11-19 05:20:53 +0800 CST
js一键生成随机颜色:randomColor
2024-11-18 10:13:44 +0800 CST
mysql int bigint 自增索引范围
2024-11-18 07:29:12 +0800 CST
【SQL注入】关于GORM的SQL注入问题
2024-11-19 06:54:57 +0800 CST
JavaScript设计模式:单例模式
2024-11-18 10:57:41 +0800 CST
goctl 技术系列 - Go 模板入门
2024-11-19 04:12:13 +0800 CST
Go 单元测试
2024-11-18 19:21:56 +0800 CST
在Rust项目中使用SQLite数据库
2024-11-19 08:48:00 +0800 CST
程序员茄子在线接单