php小編西瓜在本文中將介紹如何使用反射遞歸迭代結構並設定欄位。反射是PHP中一種強大的特性,它允許我們在運行時獲取並操作類別、方法、屬性等資訊。遞歸迭代結構是一種常用的處理方式,它可以幫助我們遍歷和操作複雜的資料結構。透過結合反射和遞歸迭代結構,我們可以輕鬆地取得並設定欄位的值,從而實現更靈活、高效的程式設計。在接下來的內容中,我們將詳細介紹這個過程,幫助讀者更好地理解並應用這個技巧。
問題內容
我想建立使用反射設定結構體欄位的程式。我讓它適用於頂級字段,但我正在努力處理嵌套結構字段。如何迭代嵌套結構字段?
type Payload struct { Type string `json:"type"` SubItem *SubItem `json:"sub_item"` } type SubItem struct { Foo string `json:"foo"` } func main() { var payload Payload setValue(&payload, "type", "test1") setValue(&payload, "sub_item.foo", "test2") } func setValue(structPtr interface{}, key string, value string) { structValue := reflect.Indirect(reflect.ValueOf(structPtr)) for i, subkey := range strings.Split(key, ".") { isLast := i == len(strings.Split(key, "."))-1 var found bool // this line is crashing with "reflect: call of reflect.Value.NumField on zero Value" for i := 0; i < structValue.NumField(); i++ { field := structValue.Type().Field(i) jsonTags := strings.Split(field.Tag.Get("json"), ",") if jsonTags[0] == subkey { found = true if isLast { if isLast { // last element // TODO set value fmt.Printf("TODO set value %s to %v", value, structValue) structValue = reflect.Indirect(reflect.ValueOf(structPtr)) } } else { structValue = reflect.Indirect(reflect.ValueOf(structValue.Field(i).Interface())) } break } } if !found { panic(fmt.Errorf("failed to find field %s", key)) } } }
解決方法
使用此功能:
func setvalue(p interface{}, key string, value interface{}) { v := reflect.valueof(p) // loop through the names in key to find the target field. for _, name := range strings.split(key, ".") { // if the value is pointer, then // - allocate value if ptr is nil. // - indirect ptr for v.kind() == reflect.ptr { if v.isnil() { v.set(reflect.new(v.type().elem())) } v = v.elem() } // we expect that the value is struct. find the // named field. v = findjsonfield(v, name) if !v.isvalid() { panic(fmt.sprintf("could not find field %s", key)) } } // set the field. v.set(reflect.valueof(value)) }
函數 findjsonfield 透過欄位的 json 標籤尋找結構體欄位:
func findJSONField(v reflect.Value, name string) reflect.Value { t := v.Type() for i := 0; i < v.NumField(); i++ { if tag, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ","); tag == name { return v.Field(i) } } return reflect.Value{} }
https://www.php.cn/link/e4848ea6b69df2c66c87e2877e74726b
以上是使用反射遞歸迭代結構並設定字段的詳細內容。更多資訊請關注PHP中文網其他相關文章!

在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

goisbeneformervicesduetoitssimplicity,效率,androbustConcurrencySupport.1)go'sdesignemphasemphasizessimplicity and效率,Idealformicroservices.2))其ConcconcurnCurnInesSandChannelsOdinesSallessallessallessAlloSalosalOsalOsalOsalOndlingConconcConccompi.3)

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang在並發性上優於C ,而C 在原始速度上優於Golang。 1)Golang通過goroutine和channel實現高效並發,適合處理大量並發任務。 2)C 通過編譯器優化和標準庫,提供接近硬件的高性能,適合需要極致優化的應用。

選擇Golang的原因包括:1)高並發性能,2)靜態類型系統,3)垃圾回收機制,4)豐富的標準庫和生態系統,這些特性使其成為開發高效、可靠軟件的理想選擇。

Golang適合快速開發和並發場景,C 適用於需要極致性能和低級控制的場景。 1)Golang通過垃圾回收和並發機制提升性能,適合高並發Web服務開發。 2)C 通過手動內存管理和編譯器優化達到極致性能,適用於嵌入式系統開發。


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

Atom編輯器mac版下載
最受歡迎的的開源編輯器

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

禪工作室 13.0.1
強大的PHP整合開發環境

WebStorm Mac版
好用的JavaScript開發工具