第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

Go 中的通用編程。避免硬編碼類型斷言

Go 中的通用編程。避免硬編碼類型斷言

Go
萬(wàn)千封印 2021-10-11 10:47:32
我正在編寫(xiě)一個(gè)通用緩存機(jī)制,我需要在結(jié)構(gòu)中設(shè)置一些屬性,只知道它們的reflect.Type、屬性名稱和reflect.Value 要在屬性中設(shè)置,但我無(wú)法避免類型斷言,這使得我的代碼不通用...func main() {    addressNew := Address{"New Address description!"}    // In the real problem, i know the reflect.Type of value, but    // the struct came to me as a interface{}, just like this method    // Return many kinds of values from redis as interface{},     // (Customer, Order, Address, Product, SKU etc), in a generic way,    // but returns the reflect.Type of value also.    interfaceSomeValue := getMyValue()    fmt.Printf("%v", interfaceSomeValue)    fmt.Println("")    // This portion of code comes from my cache mechanism, that is a library     // used by other projects. My cache lib really can't know all others    // type structs to perform the type assertion, but the cache mechanism know     // the reflect.Type of the interface.     // If you try at this way, will cause a panic by try to access a FieldByName    // in a interface, because the Customer comes from getMyValue and     // becomes a interface{}, and now a type assertion is     // required -> http://play.golang.org/p/YA8U9_KzC9    newCustomerNewAttribute := SetAttribute(&interfaceSomeValue, "Local", interface{}(addressNew), reflect.TypeOf(Customer{}))    fmt.Printf("%v", newCustomerNewAttribute)    fmt.Println("")}func SetAttribute(object interface{}, attributeName string, attValue interface{}, objectType reflect.Type) interface{} {    if reflect.ValueOf(object).Kind() != reflect.Ptr {        panic("need a pointer")    }    value := reflect.ValueOf(object).Elem()    field := value.FieldByName(attributeName)    valueForAtt := reflect.ValueOf(attValue)    field.Set(valueForAtt)    return value.Interface()}
查看完整描述

1 回答

  • 1 回答
  • 0 關(guān)注
  • 206 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)