golang動態(tài)創(chuàng)建類的示例代碼
更新時間:2023年06月27日 09:00:00 作者:蒼山落暮
這篇文章主要介紹了golang動態(tài)創(chuàng)建類的實例代碼,本文通過實例代碼給大家講解的非常詳細,需要的朋友可以參考下
動態(tài)創(chuàng)建類
(1.)使用反射創(chuàng)建類
import `reflect` var typeRegistry = make(map[string]reflect.Type) func RegisterType(elem interface{}) { t := reflect.TypeOf(elem).Elem() typeRegistry[t.Name()] = t } func NewStruct(name string) (interface{}, bool) { elem, ok := typeRegistry[name] if !ok { return nil, false } return reflect.New(elem).Elem().Interface(), true }
(2.)使用示例
// 定義結(jié)構(gòu)體 type Student struct { Name string Age int } // 初始化時注冊類型 func init() { RegisterType((*Student)(nil)) } // 獲取對象 func getObj(structName string) (*Student, error) { st, ok := NewStruct(structName) if !ok { return nil, errors.New("new struct not ok") } student, ok := st.(Student) if !ok { return nil, fmt.Errorf("assert st to Student error,st:%T", st) } // 給結(jié)構(gòu)體字段賦值 student.Name = "jones" student.Age = 18 return &student, nil } func main(){ // 獲取一個對象 stu := getObj("Student") fmt.Printf("stu:%+v",stu) }
參考鏈接
https://blog.csdn.net/qq_41257365/article/details/114108970
https://blog.csdn.net/whatday/article/details/113773167
到此這篇關(guān)于golang動態(tài)創(chuàng)建類的文章就介紹到這了,更多相關(guān)golang動態(tài)創(chuàng)建類內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Golang實現(xiàn)HTTP編程請求和響應(yīng)
本文主要介紹了Golang實現(xiàn)HTTP編程請求和響應(yīng),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-08-08