Function Types as Interface Values

SOLID五原则实战:PHP面向对象设计的五大交通规则 SOLID是面向对象设计中最基础、最普适的五大核心原则,涵盖单一职责、开闭原则、里氏替换、接口隔离与依赖倒置。其本质并非抽象理论,而是应对代码修改雪崩、扩展即破坏、继承失稳、接口臃肿和高层耦合等高频工程问题的系统性解法。在PHP这类动态语言中,interface轻量契约与依赖注入容器天然支撑SOLID落地,使职责拆分、策略扩展、类型安全与解耦实践更高效。本文聚焦真实PHP项目演进,通过订单、用户、支付等典型场景,展示如何用SOLID提升可维护性、可测试性与需求响应速度。 阅读详情

Function typesin Go can also have methods. It’s hard to see, at first, why this would beuseful.

go 的Function types也可以拥有methods。它让人费解,首先这有什么用途。

 There are two side effects to the fact thatfunction types can have methods in Go:

go的functions types拥有methods有个作用:

 firstly, since any type that can have methodscan satisfy an interface, function types in Go can also be boxed into validinterface types.

第一:任何type都可以具有methods来满足某个interface. go的functions types 也能能够装箱进一个可用的interface类型中。

Secondly, sincemethods in Go can have either pointer or value receivers, we can use methods onfunction pointers to switch the function being pointed to in the method’s callingcontext.

第二.go类型中的methods可以是pointer作为接收者也可以是value类型作为接收者;我们可以使用receiver 为functionpointers的methods 来切换函数的指向在该metho的调用过程中。

That’s a bitheady at first, so let’s go through those two things in order.

这听起来让人兴奋,来让我们逐步了解这两见事情。

First, the mostobvious way to make a function type also satisfy an interface is to pick aninterface with only one method. Keeping it simple, let’s define an add function like wedid above, but we’ll give it an Error() stringmethod. In Go,any type that has an Error() stringmethod is avalid error type, so our function can serve as both a function and an error.

type binFunc func(int, int) int

func add(x, y int) int {
    return x + y
}

func (f binFunc) Error() string {
    return "binFunc error"
}

func main() {
    var err error
    err = binFunc(add)
    fmt.Println(err)
}

函数签名和函数类型:

Ø  函数签名:输入和输入参数类型和顺序构成函数签名,与函数名无关;

Ø  定义函数类型时使用的是匿名函数模式:typeFuncType func(xxx)xxx,函数类型关注的是函数签名;

Ø  只要一个函数的函数签名和某个函数类型一致,该函数就可以强制转换为该函数类型的一个变量;

转换以后,就可以调用该函数类型的任何其他方法

You can run thistotally useless example on the Go Playground.

It’s worthnoting that in this case, we had to perform a type conversion to convert thefunction add, which is oftype func(int, int) int to type binFunc. This may seemlike an onerous(繁琐) misfeature(不好特性) of the Go runtime, but what if there was another valid conversion for func(int, int) int that wouldimplement error:

type loudBinFunc func(int, int) int

func (f loudBinFunc) Error() string {
    return "THIS ERROR IS A LOT LOUDER"
}

If both binFunc and loudBinFunc are defined, theruntime wouldn’t know how to convert our add function. Evenif there is only one valid implementation of an interface for a given type, theruntime will not perform the conversion for us automatically. It seems veryannoying (恼人)at first, but it makes it easier towrite bug-free code.(健壮代码)

总结:手动强制转换是必须的,go是强类型语言,它保证代码的健壮性和无歧义

In the standardlibrary, we can see an example of using a function type to satisfy an interfacein the net/httppackage. The http.Handler type is the interface used by the standard library to register httphandlers:

type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}

There’s also an http.HandlerFunc type, which is just a wrapper around func(http.ResponseWriter, *http.Request)that satisfies http.Handler. This allows us to use either a function or a struct as a web handler. The endresult is that we get both the http.Handle and http.HandleFuncfunctions, whichmakes it a bit more convenient to write web handlers.

Now that we’veestablished how methods on functions allow us to satisfy an interface, I’llshow a slightly more esoteric usage that turns out to be remarkably useful:let’s stick some functions in a json document.

现在我们实现了funcitons的methods怎么允许我们实现一个接口,我会略微介绍一个深奥的用法,该用法被证明非常有用。

The encoding/json package in the standardlibrary is the normal way to encode and decode json documents. This package isinterface-based; it defines an interface,json.Unmarshaler, that is to beused in the unmarshaling of json documents:

type Unmarshaler interface {
    UnmarshalJSON([]byte) error
}

That is, if youdefine this method, the encoding/jsonpackage will usethis method when unpacking json data; otherwise, it attempts to figure out whatto do on its own (and generally gets it correct). Let’s stick with the binFuncexample, but this time, we’ll stick some binary functions in a jsondocument. We’ll start with the tired old binFuncdefinition:

type binFunc func(int, int) int

Since functionsthemselves do not have any persistent data, we need somewhere to registernames. We can use a map[string]binFunc to store our functions with their associated names:

var fnRegistry = map[string]binFunc{
    "add": func(x, y int) int { return x + y },
    "sub": func(x, y int) int { return x - y },
    "mul": func(x, y int) int { return x * y },
    "div": func(x, y int) int { return x / y },
    "mod": func(x, y int) int { return x % y },
}

n Go, if weattempt to retrieve a value from a map with a nonexistent key, the retrieval operation will return the zero value for the giventype (if you’re asking “but what if we legitimately put nil into that map?”then see here). For functiontypes, the zero value is always nil, so we can justtest against nil to see if we’ve retrieved a value. Now we need to actuallyimplement the UnmarshalJSONmethod on our binFunc type. Since wewant to make changes that are seen by the caller of the function, we want toimplement UnmarshalJSON with a pointer receiver, and since we know we want a string, we justpiggy-back of the existing string unmarshaling capabilities of the standardjson package.

func (fn *binFunc) UnmarshalJSON(b []byte) error {
    // start by unmarshaling the name of the function that we want
    var name string
    if err := json.Unmarshal(b, &name); err != nil {
        return err
    }

    // get the function out of our function registry
    found := getBinFunc(name)
    if found == nil {
        // return a descriptive error if we can't find the function
        return fmt.Errorf("unknown function in (*binFunc)UnmarshalJSON: %s", name)
    }

    // dereference the pointer receiver, so that the changes are visible to the caller
    *fn = found
    return nil
}

With thatdefined, we can now unmarshal a binFunc from a json document. See here for thefull, runnable examplethat unpacks just one function, and here’s an example of using this tounpack a list of functions. Of course, this is just the tip of the iceberg, butit shows what types of things can be done with this technique.

上文中完整源码:

package main

import (
	"encoding/json"
	"fmt"
	"log"
)

var jsonDoc = []byte(`"add"`)

var registry = map[string]binFunc{
	"add": func(x, y int) int { return x + y },
	"sub": func(x, y int) int { return x - y },
	"mul": func(x, y int) int { return x * y },
	"div": func(x, y int) int { return x / y },
	"mod": func(x, y int) int { return x % y },
}

type binFunc func(int, int) int

func (fn *binFunc) UnmarshalJSON(b []byte) error {
	var name string
	if err := json.Unmarshal(b, &name); err != nil {
		return err
	}

	// get the function out of our function registry
	found := registry[name]
	if found == nil {
		// return a descriptive error if we can't find the function
		return fmt.Errorf("unknown function in (*binFunc)UnmarshalJSON: %s", name)
	}

	// dereference the pointer receiver, so that the changes are visible to the caller
	*fn = found
	return nil
}

func main() {
	var fn binFunc
	if err := json.Unmarshal(jsonDoc, &fn); err != nil {
		log.Fatal(err)
	}

	x := fn(5, 12)
	fmt.Println(x)
}











numpy.square() 深度解析:dtype 推导、ABI 兼容与生产避坑 NumPy 的 square() 并非简单数学函数,而是基于输入数据类型(dtype)动态推导输出精度的向量化 ufunc。其底层依赖 C 扩展实现,行为受 NumPy 版本演进、ABI 兼容性及类型安全规则严格约束。在科学计算与 AI 工程中,它直接影响内存分配效率、跨库协同稳定性(如 mmcv/onnxruntime 冲突)和实时性能表现。理解其 dtype 自动提升机制(如 int8→int16)、__array_function__ 协议适配要求,以及 NumPy 1.x 与 2.x 的断裂点(如 阅读详情

相关推荐

本体论——AI 圈正在悄悄换底层操作系统

文章摘要: 本体论(Ontology)正成为企业级AI落地的关键技术,从哲学概念演变为工程化基础设施。传统知识图谱(ABox层)仅存储数据,而本体论(TBox层)赋予系统推理能力,实现开放世界假设下的自动逻辑推导。Palantir以本体论为核心构建企业知识操作系统,其AIP平台通过"Proposal工作流"实现AI驱动的业务闭环,结合三层架构(语义建模、关系定义、动态操作)解决权限控制与审计难题。国内厂商如用友、悦点科技等也在布局本体智能体。当前AI工程化需突破Prompt优化层面,通过本体论构建模型可理解

528

PHP 7迁移实战:从兼容性扫描到错误处理重构

PHP 7标志着Zend引擎的彻底重写,其核心变化远超语法升级——包括zval内存结构压缩、Error类引入、OPcache默认启用及废弃函数移除等底层演进。理解这些原理,是规避运行时行为突变(如empty()对0.0判断差异、mysql_*函数彻底消失)的前提。其技术价值在于性能跃升(foreach快100%、isset()查键快5倍)与类型安全强化,广泛应用于高并发Web服务、遗留系统重构及SaaS平台升级场景。本文聚焦PHP 7迁移中真实高频雷区,结合phpstan静态分析、Docker沙盒验证与st

weixin_33845881的博客 423

论文阅读——Bayesian Knowledge Fusion(贝叶斯知识融合)

该篇论文解决了不确定环境中的信息融合问题。想象一下,有多位专家针对同一情况构建概率模型,我们希望汇总他们提供的信息。直接合并每个信息可能会遇到几个问题。例如,专家们可能不同意某个事件发生的概率,或者他们可能不同意两个事件之间因果关系的方向(例如,一个人认为 A 导致 B,而另一个人认为 B 导致 A)。他们甚至可能不同意概率网络中一组变量之间的整个依赖结构。

qq_64164071的博客 1503

Java中的函数式编程(二)函数式接口Functional Interface

写在前面 前面说过,判断一门语言是否支持函数式编程,一个重要的判断标准就是:它是否将函数看做是“第一等公民(first-class citizens)”。 函数是“第一等公民”,意味着函数和其它数据类型具备同等的地位——可以赋值给某个变量,可以作为另一个函数的参数,也可以作为另一个函数的返回值。 Java 8是通过函数式接口,赋予了函数“第一等公民”的特性。 本文将详细介绍Java 8中的函数式接口。 本文的示例代码可从gitee上获取: https://gitee.com/cnmemset/

anyuanwai的博客 4718

CAN总线开发必看:报文发送类型全解析(含Cycle/Event/CE/IfActive对比)

本文深入解析CAN总线开发中的四种报文发送类型(Cycle/Event/CE/IfActive),对比其核心特征与工程应用场景。通过典型ECU交互案例和决策矩阵,帮助开发者根据实时性、总线效率等需求选择最优方案,并详解信号发送模式与恢复机制,提升车载网络通信可靠性。

weixin_30632089的博客 318

【LCMM实战指南】从增长混合模型到潜在类别轨迹分析的纵向数据建模

本文深入解析了LCMM(潜在类别混合模型)在纵向数据建模中的应用,对比了LCGA与GMM的核心差异与选择策略。通过R语言lcmm包的实战演练,详细展示了从数据模拟、模型拟合、类别数选择到结果解读的全流程,为识别数据中不同的发展轨迹亚型提供了系统指南。

weixin_29070861的博客 384

systemctl start nginx timeout

昨儿个研究docker ,搭建私有仓库。想着用nginx代理一下仓库地址。方式使用80端口,于是愉快的下载,编辑,安装nginx。创建nginx.service作为系统启动服务。 结果......,多折腾了2个小时。。。。因为systemctl start nginx 的时候总是timeout。实际上nginx已经起来了。 顿时一阵baidu,bing,...

weixin_34306676的博客 400

fastbin attack快速入门

0x01 fastbin简介 Fastbin包含0x20~0x80大小bin的数组指针,用于快速分配小堆块。fastbin按照单链表结构进行组织,相同大小的bin在同一个链表中,fd指向下一个bin,采用LIFO(Last In First Out)机制。在fastbin中,堆块的inuse标志都为1,处于占用状态,防止chunk释放时进行合并,加快小堆块的分配。 正常fastbin的使用 通过这个简单的案例来了解fastbin的单链表结构,malloc和free的过程。 #include<stdio

abelxu 1571

AccessGuard v0.2:用户与角色管理 — TypeScript 接口、类型别名与函数重载深度实战

运行环境:在传统 JavaScript 项目中,一个"用户对象"通常长什么样?取决于你的运气和项目文档的质量。考虑以下三个不同项目中的用户对象定义: 三个项目,三种完全不同的用户形状。在一个微前端或中台系统中,当这些用户对象需要流经统一的权限检查模块时,会发生什么?——运行时类型错误。你调用 时,项目 A 的用户会直接报错( 是字符串,没有 方法)。项目 B 的用户可能正常工作但字段命名不一致导致逻辑分支混乱。项目 C 的用户则因为 是一个嵌套对象而非数组, 函数完全失效。这种混乱的根源在于:Java

我的博客 307

android usb读写,安卓(Android)下如何开发USB NFC读写器app

对安卓工程师来说,在安卓下使用USB设备需要了解很多硬件的内容,这可能会导致工程周期的延长或者app的不稳定。为了将这种风险降到最低,友我科技发布了NFC读写器在安卓下的sdk,使用NFC读写器的类接口,安卓工程师就可以直接调用NFC读写器了,简单可靠。NFC读写器的安卓库文件为:yoworfidreader.jar在ADT工程中导入yoworfidreader.jar库文件,即可在工程中引用NF...

weixin_36433781的博客 827

基于非接触式微波雷达设计的睡眠监控系统_323

本项目设计了一种基于非接触式微波雷达的睡眠监控系统,通过高精度的生理信号采集与分析,帮助用户全面了解自身的睡眠状态和健康状况。系统采用60GHz频段的R60ABD1毫米波雷达模块,实现对人体呼吸频率、心率、活动状态、体动幅度等参数的非接触式测量;结合MLX90614红外体温传感器,能够实时监测人体体温。此外,系统通过蜂鸣器报警和数据上云功能,及时向用户反馈异常生理指标,确保健康风险早期预警。数据通过ESP8266-WIFI模块上传至华为云物联网平台,用户可通过Android手机APP和Windows上位机远

505

Ramda Adjunct与TypeScript完美结合:类型定义与类型安全实践

Ramda Adjunct是最受欢迎且最全面的Ramda功能扩展工具集,提供了丰富的实用函数和完善的文档。本文将深入探讨如何通过TypeScript类型定义提升Ramda Adjunct的开发体验,确保函数调用的类型安全,帮助开发者构建更健壮的函数式应用。 ## 为什么选择Ramda Adjunct+TypeScript组合? 在函数式编程中,类型安全是保障代码质量的关键。Ramda Adju

gitblog_00028的博客 696

18、地下矿山中人工智能在区分真实微震事件与噪声信号的应用

本文提出一种基于遗传编程(GP)的新型经验模型,用于地下矿山中真实微震事件与噪声信号(特别是爆破信号)的自动区分。针对传统方法和常见机器学习算法存在的黑箱问题、过拟合及准确性不足等局限,GP模型通过符号回归和进化机制生成可解释的数学表达式,具备自动特征选择能力,有效提升了分类准确率。研究使用包含100个样本的真实数据库,结合敏感性分析优化模型参数,并与线性判别分析(LDA)进行对比,结果表明GP模型在分类性能上更具优势。该模型可应用于实时微震监测系统,提高矿山安全生产水平,降低误判带来的成本开销,具有良好的

assembly8low的博客 97

cann/runtime随机数生成示例

This sample demonstrates how to use CANN Runtime `aclrtRandomNumAsync` API to generate random numbers. Supports multiple random number distribution types and data types, used to meet random number gen

gitblog_01052的博客 623

Scale-up,scale-out技术概述

本文系统分析了Scale-up与Scale-out两种扩展技术在现代计算中的应用与发展。Scale-up通过增强单节点性能,适用于高耦合任务,而Scale-out通过横向扩展节点,实现高可用性和无限扩展。在芯片层面,Chiplet技术推动Scale-up发展;在数据中心层面,二者协同工作构建强大集群。光模块在长距离高带宽传输中发挥关键作用。文章对比了NVIDIA、AMD和Broadcom三家公司的技术路线,指出NVIDIA采用封闭生态,AMD选择开放标准,Broadcom则主导底层连接技术。未来发展方向将聚

元直的博客 1452

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

TypeScript 快速入门:从 JavaScript 到类型安全的第一步

核心痛点:JavaScript 的灵活是双刃剑。当项目从 1000 行增长到 10000 行、团队从 1 人扩展到 10 人,动态类型变成最大负债:函数参数类型成谜、对象属性重构全凭运气、第三方库升级后全线崩溃。TypeScript 是社区对"大规模 JavaScript 可持续工程化"交出的事实标准答案。适配人群:具备 JavaScript ES6+ 基础,首次接触 TypeScript 的前端工程师、全栈开发者、Node.js 后端开发者。

我的博客 376

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

3 步让一张照片开口说话:SadTalker 完整上手指南

你手里有张人像照片和一段语音,想让它"开口说话"?SadTalker 就是干这个的:一张静态照片加一段音频,输出一段带口型、带表情、带头部动作的说话视频,全程本地运行,免费开源。这篇 SadTalker 上手教程带你在 10 分钟内跑通第一次生成,并给出常用 SadTalker 参数说明。 ## 先听结果:SadTalker 能做出什么 [![SadTalker 说话人脸动画效果,参考视频眨眼

gitblog_00623的博客 988

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

CANN/GE形状推理功能分析

### 1.1 Problem Definition In deep learning graph compilers, Shape inference (InferShape) is a fundamental capability: given an operator's input Shape, attributes, and possibly input data values, det

gitblog_00947的博客 1138

轻松处理栅格数据:intro-gispro中Rasterio读写、波段计算与重投影指南

intro-gispro 是《Introduction to GIS Programming》一书的官方代码示例仓库,面向初学者系统讲解如何用 Python 处理地理空间数据。本指南带你使用其中的 Rasterio 章节,快速掌握**栅格数据读取、元数据解析、NDVI 波段计算、结果写出与重投影**五大核心技能,帮助你从零上手遥感栅格处理 🌍 ## 为什么选择 Rasterio 处理栅格数据?

gitblog_00702的博客 430

昇腾CANN/GE编码红线

### 1. Prohibit Hardcoding Sensitive Information and Using Prohibited Sensitive Words 1. Hardcoding plaintext passwords, keys, and other high-level sensitive data in source code. 2. Having deprecated

gitblog_00724的博客 361

CANN/ge设计文档模板

This section should describe the purpose of the document. It should identify the readers. It should explain which product's software requirements and design this requirements document describes. ## S

gitblog_00482的博客 683

Vue3+TypeScript实战:组合式API与类型系统深度结合提升代码质量

在现代前端开发中,响应式编程和类型安全是构建健壮应用的两大基石。Vue3的组合式API通过函数式编程范式,实现了逻辑的高效复用与组织;而TypeScript的静态类型系统则能在编译阶段捕获潜在错误,显著提升代码的可靠性和可维护性。将两者深度结合,不仅能获得更精准的自动补全和类型推断,还能在复杂业务场景下(如大型商城、后台管理系统)确保数据流和组件通信的可靠性。本文聚焦于这一技术价值,通过实战技巧,例如利用泛型增强组合式函数的类型安全、使用`PropType`严格定义组件Props,以及通过`shallowR

weixin_34226706的博客 403

TypeScript 泛型工具实战:3 种高级模式构建可复用 React 组件类型

本文深入探讨了TypeScript泛型工具在React组件开发中的高级应用,通过Pick、Omit、Partial和Record等核心工具,实现精确控制Props、动态表单状态切换和配置化组件等三大典型场景,显著提升代码的类型安全性和可复用性。

agcozdwdfvds08078的博客 358

TypeScript 5.5 类型守卫实战:3种自定义守卫优化复杂数据处理函数

本文深入探讨TypeScript 5.5中自定义类型守卫的实战应用,通过3种典型守卫模式(精确对象属性守卫、类型安全函数调用守卫和复合类型守卫)优化复杂数据处理函数。文章结合代码示例展示如何提升类型安全性、代码可维护性和开发体验,特别适合处理API响应和动态数据结构场景。

385
上一篇: Go语言-闭包
下一篇: Error Handling In Go, Part II
千年的塔
博客等级 码龄19年 322粉丝 198原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值