php小编子墨在这里分享一个关于如何重用第三方包中的结构并更改单个字段编组行为的技巧。当我们使用第三方包时,有时候我们需要对其中的某个字段进行自定义编组。本文将介绍一个简单的方法,可以通过继承和重写的方式来实现这一目标,既能重用原有的结构,又能满足个性化需求。接下来让我们一起来看看具体的实现方法吧!
问题内容
假设我想将一个结构编组到 YAML 中,并且该结构已经定义了其所有 YAML 标记,但有一个我想要更改的标记除外。如何在不更改结构本身的情况下更改此单个字段的行为?假设该结构来自第三方包。
这是一个要演示的示例,以及我的最佳尝试。假设 User
结构(及其关联的 Secret
结构)来自第三方包,因此我们无法修改它们。
package main import ( "fmt" "gopkg.in/yaml.v2" ) type User struct { Email string `yaml:"email"` Password *Secret `yaml:"password"` } type Secret struct { s string } // MarshalYAML implements the yaml.Marshaler interface for Secret. func (sec *Secret) MarshalYAML() (interface{}, error) { if sec != nil { // Replace `"<secret>"` with `sec.s`, and it gets the desired // behavior. But I can't change the Secret struct: return "<secret>", nil } return nil, nil } func (sec *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error { var st string if err := unmarshal(&st); err != nil { return err } sec.s = st return nil } // My best attempt at the solution: type SolutionAttempt struct { User } func (sol *SolutionAttempt) MarshalYAML() (interface{}, error) { res, err := yaml.Marshal( struct { // I don't like having to repeat all these fields from User: Email string `yaml:"email"` Password string `yaml:"password"` }{ Email: sol.User.Email, Password: sol.User.Password.s, }, ) if err != nil { return nil, err } return string(res), nil } func main() { user := &User{} var data = ` email: [email protected] password: asdf ` err := yaml.Unmarshal([]byte(data), user) if err != nil { fmt.Printf("errors! %s", err) return } buf, err := yaml.Marshal(user) if err != nil { fmt.Printf("errors! %s", err) return } // Without touching User or Secret, how can I unmarshall an // instance of User that renders the secret? fmt.Printf("marshalled output:\n%s\n", buf) /////////////////////////////////////////////////////// // attempted solution: /////////////////////////////////////////////////////// sol := &SolutionAttempt{} var data2 = ` user: email: [email protected] password: asdf ` err = yaml.Unmarshal([]byte(data2), sol) if err != nil { fmt.Printf("errors! %s", err) return } buf, err = yaml.Marshal(sol) if err != nil { fmt.Printf("errors! %s", err) return } fmt.Printf("attempted solution marshalled output:\n%s\n", buf) }
这是上述代码的 Go Playground 链接:https://go.dev/play/p/ojiPv4ylCEq
解决方法
这根本不可能。
你的“最佳尝试”就是正确的道路。
以上是如何重用第三方包中的结构,同时更改单个字段的编组行为?的详细内容。更多信息请关注PHP中文网其他相关文章!

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建筑物内currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用辅助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

CustomInterfacesingoarecrucialforwritingFlexible,可维护,andTestableCode.TheyEnableDevelostOverostOcusonBehaviorBeiroveration,增强ModularityAndRobustness.byDefiningMethodSigntulSignatulSigntulSignTypaterSignTyperesthattypesmustemmustemmustemmustemplement,InterfaceSallowForCodeRepodEreusaperia

使用接口进行模拟和测试的原因是:接口允许定义合同而不指定实现方式,使得测试更加隔离和易于维护。1)接口的隐式实现使创建模拟对象变得简单,这些对象在测试中可以替代真实实现。2)使用接口可以轻松地在单元测试中替换服务的真实实现,降低测试复杂性和时间。3)接口提供的灵活性使得可以为不同测试用例更改模拟行为。4)接口有助于从一开始就设计可测试的代码,提高代码的模块化和可维护性。

在Go中,init函数用于包初始化。1)init函数在包初始化时自动调用,适用于初始化全局变量、设置连接和加载配置文件。2)可以有多个init函数,按文件顺序执行。3)使用时需考虑执行顺序、测试难度和性能影响。4)建议减少副作用、使用依赖注入和延迟初始化以优化init函数的使用。

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,执行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,确保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,确保Allimizegoroutines,确保AllizeNizeGoROutines,确保AllimizeGoroutines


热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

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

热门文章

热工具

WebStorm Mac版
好用的JavaScript开发工具

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

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