3

作为一个学习者, 对 接口 的认知. 以及一些有趣的想法

 1 year ago
source link: https://studygolang.com/articles/36039
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

作为一个学习者, 对 接口 的认知. 以及一些有趣的想法

jingle · 大约23小时之前 · 276 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览    

接口 是 一组相关动作名/行为名的 组名

由于 接口 只能控制 方法名 和 参数的个数与类型,  接口 无法控制代码能做什么

    实现接口的类型对象 A, 挂羊头卖羊肉

    实现接口的类型对象 B, 挂羊头卖猪肉

    实现接口的类型对象 C, 挂羊头卖人造植物肉

    实现接口的类型对象 D, 挂羊头卖春

所以 接口 的用途很小, 只能作为 函数定义中的形参.

1 冗余用法, 毫无意义-声明接口只为调用动态值的接口方法: 

    var 接口对象 接口类型;       var 类型对象 类型

    接口对象 = 类型对象; 

    接口对象.类型对象的接口方法()    

2 作为函数定义中的形参, 接收实现该接口的对象, 再利用

    func do( 接口对象 接口类型 ){

            接口对象.动态值实现的接口方法()

目前几乎所有教学都教接口的第一种用法,  谁能告诉我第一种方式的用途?

接口倒让我有些其他想法:  如果有一种类型能代表 一组已经实现的方法, 那么也应该有点用处.

伪代码如下:

type Actions actions{

    fn Action1( a... fn() ) {   Print( "a" );   if... a[0]()   }

    fn Action2( b... fn() ) {   Print( "b" );   if... b[0]()   }

class X{

    @Actions{   // 表示 可将花括号中内容用于 actions: "Actions"

        do1(){    Print( "is finished" )     }  

        do2(){    Print( "已完成" )     }  

var x = new( X ) 

x.Action1( do1 )   // output: a is finished

x.Action2( do1 )   // output: b is finished

x.do2()                // output: 已完成

另外, 讲点经历.  我尝试读了一下http包 又链接到text包,  发现很难,   函数, 方法, 私有, 公用, 不同文件,  无法直觉式的认出它是谁, 等认识它是谁时, 前面的逻辑又乱了甚至想不起来.   比如标识符 parse .  太脑力冗余了.    路由器那块 handler接口 神一般的存在, 我得话时间看看,  不过先得把模板这块内容递归回来


有疑问加站长微信联系(非本文作者)

280

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK