无论Go中元素的顺序如何,如何在语义上比较结构与嵌套切片是一个常见问题。在Go语言中,结构体是一种聚合数据类型,而切片则是一种动态数组。php小编子墨将为您解答这个问题。在比较结构体时,只有当所有成员都是可比较的类型时,它们才是可比较的。而在比较嵌套切片时,我们需要逐级比较切片中的元素。如果切片的元素类型是不可比较的,我们需要使用递归方法来比较切片的每个元素。无论是结构体还是嵌套切片,我们都可以通过遍历元素来比较它们。
问题内容
给出下一个类型结构定义:
type A struct { Id int Bs []B Sub C } type B struct { Id int Str string } type C struct { Id int Ds []D } type D struct { Id int Num int }
我想测试 A 的接下来两个实例在语义上是否相等,无论所有层次结构级别中切片元素的顺序如何。
var want = &A{ Id: 1, Bs: []B{{Id: 10, Str: "b10"}, {Id: 20, Str: "b20"}}, Sub: C{ Id: 100, Ds: []D{{Id: 101, Num: 1001}, {Id: 102, Num: 1002}}, }, } var got = &A{ Id: 1, Bs: []B{{Id: 20, Str: "b20"}, {Id: 10, Str: "b10"}}, Sub: C{ Id: 100, Ds: []D{{Id: 102, Num: 1002}, {Id: 101, Num: 1001}}, }, }
断言比较应返回true
解决方法
包 cmp 旨在成为 reflect.DeepEqual
的更强大、更安全的替代品用于比较两个值在语义上是否相等。
这里是语义相等结构比较的完整实现,无论切片元素在所有层次结构级别的顺序如何。
文件source.go
package main type A struct { Id int Bs []B Sub C } type B struct { Id int Str string } type C struct { Id int Ds []D } type D struct { Id int Num int } func NewA() *A { return &A{ Id: 1, Bs: []B{{Id: 20, Str: "b20"}, {Id: 10, Str: "b10"}}, Sub: C{ Id: 100, Ds: []D{{Id: 102, Num: 1002}, {Id: 101, Num: 1001}}, }, } }
文件source_test.go
package main import ( "fmt" "testing" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" ) var want = &A{ Id: 1, Bs: []B{{Id: 10, Str: "b10"}, {Id: 20, Str: "b20"}}, Sub: C{ Id: 100, Ds: []D{{Id: 101, Num: 1001}, {Id: 102, Num: 1002}}, }, } func TestNewA(t *testing.T) { got := NewA() less := func(x, y any) bool { switch xv := x.(type) { case B: yv := y.(B) return fmt.Sprintf("%d-%s", xv.Id, xv.Str) < fmt.Sprintf("%d-%s", yv.Id, yv.Str) case D: yv := y.(D) return fmt.Sprintf("%d-%d", xv.Id, xv.Num) < fmt.Sprintf("%d-%d", yv.Id, yv.Num) default: return false } } if diff := cmp.Diff(want, got, cmpopts.SortSlices(less)); diff != "" { t.Errorf("mismatch:\n%s", diff) } }
以上是无论 Go 中元素的顺序如何,如何在语义上比较结构与嵌套切片的详细内容。更多信息请关注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
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

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

Dreamweaver Mac版
视觉化网页开发工具