当前位置:网站首页>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 ...
边栏推荐
- 没有sXid,suid&sgid将进入险境!-尚文网络xUP楠哥
- Recursion: depth first search
- Separable bonds and convertible bonds
- Advanced redis applications [password protection, data persistence, master-slave synchronization, sentinel mode, transactions] [not completed yet (semi-finished products)]
- 2022-07-02:以下go语言代码输出什么?A:编译错误;B:Panic;C:NaN。 package main import “fmt“ func main() { var a =
- ffmpeg之 一张/多张图片合成视频
- [leetcode question brushing day 34] 540 Unique element in array, 384 Disrupt array, 202 Happy number, 149 Maximum number of points on a line
- Web会话管理安全问题
- golang xxx. Go code template
- Recursive use and multi-dimensional array object to one-dimensional array object
猜你喜欢

Summary of electromagnetic spectrum

Cnopendata China Customs Statistics

Is pytorch difficult to learn? How to learn pytorch well?

js中#号的作用

Bisher - based on SSM pet adoption center

Web session management security issues
![[home push IMessage] software installation virtual host rental tothebuddy delay](/img/e7/eb20a773e4b674962f856d179a3769.jpg)
[home push IMessage] software installation virtual host rental tothebuddy delay

Numpy warning visibledeprecationwarning: creating an ndarray from ragged needed sequences

105. SAP UI5 Master-Detail 布局模式的联动效果实现明细介绍

The latest analysis of the main principals of hazardous chemical business units in 2022 and the simulated examination questions of the main principals of hazardous chemical business units
随机推荐
Mongodb master profile
Half of 2022 is over, so we must hurry up
Download and install captura and configure ffmpeg in captura
[Blue Bridge Road -- bug free code] interpretation of some codes of matrix keyboard
Recursion: one dimensional linked lists and arrays
C language hashtable/hashset library summary
递归使用和多维数组对象变一维数组对象
node,npm以及yarn下载安装
105. SAP UI5 Master-Detail 布局模式的联动效果实现明细介绍
golang xxx. Go code template
错误 C2694 “void Logger::log(nvinfer1::ILogger::Severity,const char *)”: 重写虚函数的限制性异常规范比基类虚成员函数
What can learning pytorch do?
Leetcode: dynamic planning template
The difference between static web pages and dynamic web pages & the difference between Web1.0 and Web2.0 & the difference between get and post
QSAR model establishment script based on pytoch and rdkit
[combinatorics] brief introduction to generating function (definition of generating function | Newton binomial coefficient | commonly used generating function | correlation with constant | correlation
MySQL MAC download and installation tutorial
Ffmpeg one / more pictures synthetic video
Nanning water leakage detection: warmly congratulate Guangxi Zhongshui on winning the first famous brand in Guangxi
pytorch难学吗?如何学好pytorch?