搜尋
首頁後端開發Golang如何重複使用第三方套件中的結構,同時變更單一欄位的編組行為?

如何重複使用第三方套件中的結構,同時變更單一欄位的編組行為?

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&#160;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&#160;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中文網其他相關文章!

陳述
本文轉載於:stackoverflow。如有侵權,請聯絡admin@php.cn刪除
使用GO開發時的安全考慮使用GO開發時的安全考慮Apr 27, 2025 am 12:18 AM

Gooffersrobustfeaturesforsecurecoding,butdevelopersmustimplementsecuritybestpracticeseffectively.1)UseGo'scryptopackageforsecuredatahandling.2)Manageconcurrencywithsynchronizationprimitivestopreventraceconditions.3)SanitizeexternalinputstoavoidSQLinj

了解GO的錯誤接口了解GO的錯誤接口Apr 27, 2025 am 12:16 AM

Go的錯誤接口定義為typeerrorinterface{Error()string},允許任何實現Error()方法的類型被視為錯誤。使用步驟如下:1.基本檢查和記錄錯誤,例如iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}。 2.創建自定義錯誤類型以提供更多信息,如typeMyErrorstruct{MsgstringDetailstring}。 3.使用錯誤包裝(自Go1.13起)來添加上下文而不丟失原始錯誤信息,

並發程序中的錯誤處理並發程序中的錯誤處理Apr 27, 2025 am 12:13 AM

對效率的Handleerrorsinconcurrentgopragrs,UsechannelstocommunicateErrors,enplionErrorWatchers,Instertimeout,UsebufferedChannels和Provideclearrormessages.1)USEchannelelStopassErtopassErrorsErtopassErrorsErrorsErrorsFromGoroutInestOthemainFunction.2)

您如何在GO中實現接口?您如何在GO中實現接口?Apr 27, 2025 am 12:09 AM

在Go語言中,接口的實現是通過隱式的方式進行的。 1)隱式實現:類型只要包含接口定義的所有方法,就自動滿足該接口。 2)空接口:interface{}類型所有類型都實現,適度使用可避免類型安全問題。 3)接口隔離:設計小而專注的接口,提高代碼的可維護性和重用性。 4)測試:接口有助於通過模擬依賴進行單元測試。 5)錯誤處理:通過接口可以統一處理錯誤。

將GO接口與其他語言的接口進行比較(例如Java,C#)將GO接口與其他語言的接口進行比較(例如Java,C#)Apr 27, 2025 am 12:06 AM

go'sinterfacesareimpliclyimplyed,與Javaandc#wheRequireexplitiCimplation.1)Ingo,AnyTypeWithTheRequiredMethodSautSautSautautapitymethodimimplementsaninternionsaninterninternionsaninterface.2)

初始功能和副作用:平衡初始化與可維護性初始功能和副作用:平衡初始化與可維護性Apr 26, 2025 am 12:23 AM

Toensureinitfunctionsareeffectiveandmaintainable:1)Minimizesideeffectsbyreturningvaluesinsteadofmodifyingglobalstate,2)Ensureidempotencytohandlemultiplecallssafely,and3)Breakdowncomplexinitializationintosmaller,focusedfunctionstoenhancemodularityandm

開始GO:初學者指南開始GO:初學者指南Apr 26, 2025 am 12:21 AM

goisidealforbeginnersandsubableforforcloudnetworkservicesduetoitssimplicity,效率和concurrencyFeatures.1)installgromtheofficialwebsitealwebsiteandverifywith'.2)

進行並發模式:開發人員的最佳實踐進行並發模式:開發人員的最佳實踐Apr 26, 2025 am 12:20 AM

開發者應遵循以下最佳實踐:1.謹慎管理goroutines以防止資源洩漏;2.使用通道進行同步,但避免過度使用;3.在並發程序中顯式處理錯誤;4.了解GOMAXPROCS以優化性能。這些實踐對於高效和穩健的軟件開發至關重要,因為它們確保了資源的有效管理、同步的正確實現、錯誤的適當處理以及性能的優化,從而提升軟件的效率和可維護性。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具