Interface{} 类型误解:揭示复杂性
在 Go 中,interface{} 类型既提供了灵活性,也提供了复杂性。然而,误解其本质可能会导致意想不到的后果,如一个令人费解的示例所示。
当尝试将非指针类型作为 interface{} 参数传递给函数并使用 json.Unmarshal 时,输出可能会令人惊讶。下面的示例演示了这种行为:
package main import ( "encoding/json" "fmt" ) func test(i interface{}) { j := []byte(`{ "foo": "bar" }`) fmt.Printf("%T\n", i) fmt.Printf("%T\n", &i) json.Unmarshal(j, &i) fmt.Printf("%T\n", i) } type Test struct { Foo string } func main() { test(Test{}) }
输出:
main.Test *interface {} map[string]interface {}
揭开神秘面纱
混乱源于界面的本质{}。它不仅仅是一个无类型容器,而是一个(值,类型)对的包装器。该接口存储对具体值及其类型的引用。
json.Unmarshal 将一个 interface{} 值作为其输入,因此我们可以直接将 i 传递给它。尝试获取其地址(与 &i 一样)是不必要的。
指针和接口
但是,如果 i 包含非指针值,则 json.Unmarshal 面临挑战。由于包无法解组为非指针,因此它会创建一个类型为interface{}的新值。这允许它选择类型,默认为map[string]interface{}。
正确的场景
对于指针场景,传递 &i 作为参数之所以有效,是因为 json.Unmarshal 取消引用指针以查找包含 *Test 值的 interface{} 值。指针确保解组发生在正确的类型中。
结论
为了避免这些混淆,请避免使用指向接口的指针。相反,将指针“放置”在接口内并直接传递它们。通过了解 interface{} 和指针之间的相互作用,开发人员可以避免意外结果并有效利用 Go 的类型系统。
以上是为什么使用非指针'interface{}”参数的'json.Unmarshal”会在 Go 中产生意外结果?的详细内容。更多信息请关注PHP中文网其他相关文章!

whentestinggocodewithinitfunctions,useexplicitseTupfunctionsorseParateTestFileSteSteTepteTementDippedDependendendencyOnInItfunctionsIdeFunctionSideFunctionsEffect.1)useexplicitsetupfunctionStocontrolglobalvaribalization.2)createSepEpontrolglobalvarialization

go'serrorhandlingurturnserrorsasvalues,与Javaandpythonwhichuseexceptions.1)go'smethodensursexplitirorhanderling,propertingrobustcodebutincreasingverbosity.2)

AnefactiveInterfaceoisminimal,clear and promotesloosecoupling.1)minimizeTheInterfaceForflexibility andeaseofimplementation.2)useInterInterfaceForeabStractionTosWapImplementations withCallingCallingCode.3)

集中式错误处理在Go语言中可以提升代码的可读性和可维护性。其实现方式和优势包括:1.将错误处理逻辑从业务逻辑中分离,简化代码。2.通过集中处理错误,确保错误处理的一致性。3.使用defer和recover来捕获和处理panic,增强程序健壮性。

Ingo,替代词Inivuntionsionializatializatializationfunctionsandsingletons.1)customInitializationfunctions hallowexpliticpliticpliticconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconcontirization curssementializatizatupsetups.2)单次固定元素限制ininconinconcurrent

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)


热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

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

热门文章

热工具

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

Atom编辑器mac版下载
最流行的的开源编辑器

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

SublimeText3 Linux新版
SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境