首页
视频
资源
登录
原
Go 行为的定义与实现
3937
人阅读
2021/1/30 16:03
总访问:
2537318
评论:
0
收藏:
0
手机
分类:
Go
![go数据类型](https://img.tnblog.net/arcimg/hb/0dd243ae49394f12beed84237bfee1a3.jpg "go数据类型") >#Go 行为的定义与实现 [TOC] tn>在Go语言中其实是不可以实现继承的,但网上有继承相关但方式。所以Go既可以算得上面向对象,也算不上面向对象。 实例的创建以及初始化 ------------ ```go package encap import "testing" type Employee struct { Id string Name string Age int } func TestCreateEmployeeObj(t *testing.T) { e := Employee{"0", "Bob", 19} e1 := Employee{Name: "Bob", Age: 20} e2 := new(Employee) // 注意这里返回的引用/指针 相当于e := &Employee{} e2.Name = "AiDaSi" // 与其他主要编程语言的主要差距是,通过实例指针访问成员不需要-> e2.Id = "1" e2.Age = 19 t.Logf("e.Id: %s e.Name: %s e.Age: %d", e.Id, e.Name, e.Age) t.Logf("e1.Id: %s e1.Name: %s e1.Age: %d", e1.Id, e1.Name, e1.Age) t.Logf("e2.Id: %s e2.Name: %s e2.Age: %d", e2.Id, e2.Name, e2.Age) } ``` ![](https://img.tnblog.net/arcimg/hb/e6afb05403584c44848dfb4c172e30d3.png) tn>如果想获取它的类型的话,我们从下图发现`e1`是实例的对象类型,`e2`是指针类型。 ```go // 使用%T获取该类型 t.Logf("e1 is %T", e1) t.Logf("e2 is %T", e2) ``` ![](https://img.tnblog.net/arcimg/hb/9bae3b25a8374502812088ad2e894e23.png) 行为方法的定义 ------------ tn>相当于c#对类对扩展方法一样 ```go // 相当于扩展方法 // 通过实例去请求的方法 func (e Employee) String() string { return fmt.Sprintf("e type: %T e.Id: %s e.Name: %s e.Age: %d Indicator: %x", e, e.Id, e.Name, e.Age, unsafe.Pointer(&e.Id)) } // 通过指针去请求的方法 func (e *Employee) IndicatorString() string { return fmt.Sprintf("e type: %T e.Id: %s e.Name: %s e.Age: %d Indicator: %x", e, e.Id, e.Name, e.Age, unsafe.Pointer(&e.Id)) } func TestBeHavior(t *testing.T) { e := Employee{"1", "Bob", 19} // 获取实例指针 t.Logf("Init: %x", unsafe.Pointer(&e.Id)) t.Logf(e.String()) t.Logf(e.IndicatorString()) } ``` tn>在这里我们一般使用第二种方式,因为是使用的同一个指针而少做类一次实例的复制 ![](https://img.tnblog.net/arcimg/hb/be15020d2a6a4b0f94e974e6ea035c89.png)
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739
👈{{preArticle.title}}
👉{{nextArticle.title}}
评价
{{titleitem}}
{{titleitem}}
{{item.content}}
{{titleitem}}
{{titleitem}}
{{item.content}}
尘叶心繁
这一世以无限游戏为使命!
博主信息
排名
6
文章
6
粉丝
16
评论
8
文章类别
.net后台框架
166篇
linux
17篇
linux中cve
1篇
windows中cve
0篇
资源分享
10篇
Win32
3篇
前端
28篇
传说中的c
4篇
Xamarin
9篇
docker
15篇
容器编排
101篇
grpc
4篇
Go
15篇
yaml模板
1篇
理论
2篇
更多
Sqlserver
4篇
云产品
39篇
git
3篇
Unity
1篇
考证
2篇
RabbitMq
23篇
Harbor
1篇
Ansible
8篇
Jenkins
17篇
Vue
1篇
Ids4
18篇
istio
1篇
架构
2篇
网络
7篇
windbg
4篇
AI
18篇
threejs
2篇
人物
1篇
嵌入式
2篇
python
13篇
HuggingFace
8篇
pytorch
9篇
opencv
6篇
最新文章
最新评价
{{item.articleTitle}}
{{item.blogName}}
:
{{item.content}}
关于我们
ICP备案 :
渝ICP备18016597号-1
网站信息:
2018-2024
TNBLOG.NET
技术交流:
群号656732739
联系我们:
contact@tnblog.net
欢迎加群
欢迎加群交流技术