golang動(dòng)態(tài)創(chuàng)建類的示例代碼
動(dò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
}
// 初始化時(shí)注冊(cè)類型
func init() {
RegisterType((*Student)(nil))
}
// 獲取對(duì)象
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(){
// 獲取一個(gè)對(duì)象
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動(dòng)態(tài)創(chuàng)建類的文章就介紹到這了,更多相關(guān)golang動(dòng)態(tài)創(chuàng)建類內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何讓shell終端和goland控制臺(tái)輸出彩色的文字
這篇文章主要介紹了如何讓shell終端和goland控制臺(tái)輸出彩色的文字的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-05-05
Go 請(qǐng)求兔子識(shí)別接口實(shí)現(xiàn)流程示例詳解
這篇文章主要為大家介紹了Go 請(qǐng)求兔子識(shí)別接口實(shí)現(xiàn)流程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
Golang實(shí)現(xiàn)HTTP編程請(qǐng)求和響應(yīng)
本文主要介紹了Golang實(shí)現(xiàn)HTTP編程請(qǐng)求和響應(yīng),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08
大多數(shù)Go程序員都走過(guò)的坑盤點(diǎn)解析
這篇文章主要為大家介紹了大多數(shù)Go程序員都走過(guò)的坑盤點(diǎn)解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
GO使用阿里云,解決go get下載項(xiàng)目慢或無(wú)法下載的情況
這篇文章主要介紹了GO使用阿里云,解決go get下載項(xiàng)目慢或無(wú)法下載的情況,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01

