我想要一个功能来检查不同地图中的重复键。
这就是我所拥有的
ma := map[string]typea mb := map[string]typeb mc := map[string]typec dup := map[string]bool{} for k := range ma{ if !dup[k] { dup[k] = true } else { return fmt.errorf("duplicate key[%v]", k) } } for k := range mb{ if !dup[k] { dup[k] = true } else { return fmt.errorf("duplicate key[%v]", k) } } for k := range mc { if !dup[k] { dup[k] = true } else { return fmt.errorf("duplicate key[%v]", k) } } return nil
我想重构它并编写一个函数
func checkDupKeys[M ~map[K]V, K comparable, V any](maps ...M) error { dup := map[K]bool{} for _, m := range maps { for k := range m { if !dup[k] { dup[k] = true } else { return fmt.Errorf("duplicate key[%v]", k) } } } return nil }
但它只能接受相同类型的映射,不能接受 typea、typeb 和 typec。
正确答案
您可以尝试使用 any
类型和反射
func checkDupKeys(maps ...any) error { dup := map[any]bool{} for i, m := range maps { t := reflect.TypeOf(m) if t.Kind() != reflect.Map { return fmt.Errorf("not a map at index: %d", i) } keys := reflect.ValueOf(m).MapKeys() for _, k := range keys { v := k.Interface() if !dup[v] { dup[v] = true } else { return fmt.Errorf("duplicate key[%v]", v) } } } return nil }
这种方法的缺点是该函数还将接受非映射参数,并且编译器不会对此发出警告。
以上是检查不同 Go Map 类型中的重复键的详细内容。更多信息请关注PHP中文网其他相关文章!

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

Go语言的错误处理通过errors.Is和errors.As函数变得更加灵活和可读。1.errors.Is用于检查错误是否与指定错误相同,适用于错误链的处理。2.errors.As不仅能检查错误类型,还能将错误转换为具体类型,方便提取错误信息。使用这些函数可以简化错误处理逻辑,但需注意错误链的正确传递和避免过度依赖以防代码复杂化。

tomakegoapplicationsRunfasterandMorefly,useProflingTools,leverageConCurrency,andManageMoryfectily.1)usepprofforcpuorforcpuandmemoryproflingtoidentifybottlenecks.2)upitizegorizegoroutizegoroutinesandchannelstoparalletaparelalyizetasksandimproverperformance.3)

go'sfutureisbrightwithtrendslikeMprikeMprikeTooling,仿制药,云 - 纳蒂维德象,performanceEnhancements,andwebassemblyIntegration,butchallengeSinclainSinClainSinClainSiNgeNingsImpliCityInsImplicityAndimimprovingingRornhandRornrorlling。

goroutinesarefunctionsormethodsthatruncurranceingo,启用效率和灯威量。1)shememanagedbodo'sruntimemultimusingmultiplexing,允许千sstorunonfewerosthreads.2)goroutinessimproverentimensImproutinesImproutinesImproveranceThroutinesImproveranceThrountinesimproveranceThroundinesImproveranceThroughEasySytaskParallowalizationAndeff

purposeoftheInitfunctionoIsistoInitializeVariables,setUpConfigurations,orperformneccesSetarySetupBeforEtheMainFunctionExeCutes.useInitby.UseInitby:1)placingitinyourcodetorunautoamenationally oneraty oneraty oneraty on inity in ofideShortAndAndAndAndForemain,2)keepitiTshortAntAndFocusedonSimImimpletasks,3)

Gointerfacesaremethodsignaturesetsthattypesmustimplement,enablingpolymorphismwithoutinheritanceforcleaner,modularcode.Theyareimplicitlysatisfied,usefulforflexibleAPIsanddecoupling,butrequirecarefulusetoavoidruntimeerrorsandmaintaintypesafety.

在Go中使用recover()函数可以从panic中恢复。具体方法是:1)在defer函数中使用recover()捕获panic,避免程序崩溃;2)记录详细的错误信息以便调试;3)根据具体情况决定是否恢复程序执行;4)谨慎使用,以免影响性能。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

SublimeText3汉化版
中文版,非常好用

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。