当前位置:网站首页>Interface embedded in golang struct
Interface embedded in golang struct
2022-07-03 03:54:00 【sandyznb】
Recently in to see context A strange usage was found in the underlying source code :struct Embedded inside interface,struct It has not been fully realized interface All interfaces of , I really didn't notice this usage before , I've only seen interface nesting interface Of , Decided to write down .
Go straight to the source :src\context\context.go
type Context interface {
Deadline() (deadline time.Time, ok bool)
Done() <-chan struct{}
Err() error
Value(key interface{}) interface{}
}cancelCtx Definition and concrete implementation of structure
type cancelCtx struct {
Context
mu sync.Mutex // protects following fields
done atomic.Value // of chan struct{}, created lazily, closed by first cancel call
children map[canceler]struct{} // set to nil by the first cancel call
err error // set to non-nil by the first cancel call
}
func (c *cancelCtx) Value(key interface{}) interface{} {
if key == &cancelCtxKey {
return c
}
return c.Context.Value(key)
}
func (c *cancelCtx) Done() <-chan struct{} {
d := c.done.Load()
if d != nil {
return d.(chan struct{})
}
c.mu.Lock()
defer c.mu.Unlock()
d = c.done.Load()
if d == nil {
d = make(chan struct{})
c.done.Store(d)
}
return d.(chan struct{})
}
func (c *cancelCtx) Err() error {
c.mu.Lock()
err := c.err
c.mu.Unlock()
return err
}timerCtx Definition and concrete implementation of structure
type timerCtx struct {
cancelCtx
timer *time.Timer // Under cancelCtx.mu.
deadline time.Time
}
func (c *timerCtx) Deadline() (deadline time.Time, ok bool) {
return c.deadline, true
}Context Interface with 4 A way , however cancelCtx only 3 A way ,Deadline() It doesn't work , and timerCtx only Deadline(), other 3 One has not been realized .
I haven't seen this kind of writing in my cognition , To implement an interface is to implement all the methods of this interface , For example, in the source code emptyCtx
type emptyCtx int
func (*emptyCtx) Deadline() (deadline time.Time, ok bool) {
return
}
func (*emptyCtx) Done() <-chan struct{} {
return nil
}
func (*emptyCtx) Err() error {
return nil
}
func (*emptyCtx) Value(key interface{}) interface{} {
return nil
}
func (e *emptyCtx) String() string {
switch e {
case background:
return "context.Background"
case todo:
return "context.TODO"
}
return "unknown empty Context"
}
var (
background = new(emptyCtx)
todo = new(emptyCtx)
)At that time, I saw this usage , Directly confused , Or I have a weak foundation ....
The embedded interface As struct An anonymous member of , You can assume this struct This is the member interface An implementation of , Regardless of struct Has it been realized interface Defined function .
type Student interface {
Run()
Walk()
}
type Pupil struct {
age int
Student
}
func NewPupil(age int) *Pupil{
return &Pupil{age: age}
}
//func (p *Pupil) Run() {
//
//}
//
//func (p *Pupil) Walk(){
//
//}
func main(){
p := NewPupil(100)
var s Student = p
fmt.Printf("%#v\n",s)
}struct Pupil It didn't come true interface Any function in , Just put Student As an anonymous member ,main The function can run normally without error , explain p It is indeed considered Student The concrete realization of .
Since there is no implementation function , How to call the interface ? The answer is Without implementation, you can't call , Once called crash. Only functions that have been implemented can be called . Noted above Run() and Walk() Let go of which ,s You can call which ...
边栏推荐
- Captura下载安装及在Captura配置FFmpeg
- Introduction to mongodb
- 毕设-基于SSM宠物领养中心
- Hutool dynamically adds scheduled tasks
- 动态规划:最长回文子串和子序列
- Summary of electromagnetic spectrum
- 『期末复习』16/32位微处理器(8086)基本寄存器
- Numpy warning visibledeprecationwarning: creating an ndarray from ragged needed sequences
- How to move towards IPv6: IPv6 Transition Technology - Shangwen network quigo
- 编译文件时报错:错误: 编码GBK的不可映射字符
猜你喜欢

CEPH Shangwen network xUP Nange that releases the power of data

Bid farewell to artificial mental retardation: Mengzi open source project team received RMB 100 million financing to help NLP develop

Hutool dynamically adds scheduled tasks

QQ小程序开发之 一些前期准备:预约开发账号、下载安装开发者工具、创建qq小程序

Cnopendata China Customs Statistics

js中#号的作用

2022 Shandong Province safety officer C certificate examination questions and Shandong Province safety officer C certificate simulation examination question bank

What is pytorch? Is pytorch a software?

2022 tea master (intermediate) examination questions and analysis and tea master (intermediate) practical examination video

Download and install captura and configure ffmpeg in captura
随机推荐
Nodejs Foundation: shallow chat URL and querystring module
【刷题篇】接雨水(一维)
[combinatorics] basic counting principle (addition principle | multiplication principle)
[embedded module] OLED display module
【DRM】DRM bridge驱动调用流程简单分析
2.14 simulation summary
简易版 微信小程序开发之页面跳转、数据绑定、获取用户信息、获取用户位置信息
阿洛对自己的思考
pytorch怎么下载?pytorch在哪里下载?
『期末复习』16/32位微处理器(8086)基本寄存器
Table structure of Navicat export database
The difference between static web pages and dynamic web pages & the difference between Web1.0 and Web2.0 & the difference between get and post
没有sXid,suid&sgid将进入险境!-尚文网络xUP楠哥
[Yu Yue education] reference materials of political communication science of Communication University of China
ffmpeg下载安装教程及介绍
[mathematical logic] predicate logic (first-order predicate logic formula | example)
Role of JS No
2022 mobile crane driver examination registration and mobile crane driver operation examination question bank
Write it down once Net travel management background CPU Explosion Analysis
Téléchargement et installation du client Filezilla