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

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

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语言 面向对象

推荐文章

JavaScript设计模式:装饰器模式
2024-11-19 06:05:51 +0800 CST
Golang 几种使用 Channel 的错误姿势
2024-11-19 01:42:18 +0800 CST
实现微信回调多域名的方法
2024-11-18 09:45:18 +0800 CST
如何优化网页的 SEO 架构
2024-11-18 14:32:08 +0800 CST
三种高效获取图标资源的平台
2024-11-18 18:18:19 +0800 CST
Go 协程上下文切换的代价
2024-11-19 09:32:28 +0800 CST
Vue3中如何处理组件的单元测试?
2024-11-18 15:00:45 +0800 CST
服务器购买推荐
2024-11-18 23:48:02 +0800 CST
ElasticSearch集群搭建指南
2024-11-19 02:31:21 +0800 CST
一些好玩且实用的开源AI工具
2024-11-19 09:31:57 +0800 CST
Rust 中的所有权机制
2024-11-18 20:54:50 +0800 CST
网络数据抓取神器 Pipet
2024-11-19 05:43:20 +0800 CST
使用Python提取图片中的GPS信息
2024-11-18 13:46:22 +0800 CST
MySQL设置和开启慢查询
2024-11-19 03:09:43 +0800 CST
JavaScript设计模式:桥接模式
2024-11-18 19:03:40 +0800 CST
JS中 `sleep` 方法的实现
2024-11-19 08:10:32 +0800 CST
回到上次阅读位置技术实践
2025-04-19 09:47:31 +0800 CST
Nginx 防止IP伪造,绕过IP限制
2025-01-15 09:44:42 +0800 CST
Golang 随机公平库 satmihir/fair
2024-11-19 03:28:37 +0800 CST
一个简单的html卡片元素代码
2024-11-18 18:14:27 +0800 CST
程序员茄子在线接单