我想創建一個結構類型的注冊表,以便動態加載“歐拉項目”問題的解決方案。但是,我當前的解決方案要求首先創建結構并將其歸零,然后才能注冊其類型:package solutionimport ( "errors" "fmt" "os" "reflect")type Solution interface { Load() Solve() string}type SolutionRegister map[string]reflect.Typefunc (sr SolutionRegister) Set(t reflect.Type) { fmt.Printf("Registering %s\n", t.Name()) sr[t.Name()] = t}func (sr SolutionRegister) Get(name string) (Solution, error) { if typ, ok := sr[name]; ok { sol := reflect.New(typ).Interface().(Solution) return sol, nil } return nil, errors.New("Invalid solution: " + name)}var solutionsRegistry = make(SolutionRegister)func Register(sol Solution) { solutionsRegistry.Set(reflect.TypeOf(sol).Elem())}func Load(s string) Solution { sol, err := solutionsRegistry.Get(s) if err != nil { fmt.Printf("Error loading solution %s (%s)\n", s, err) os.Exit(-1) } sol.Load() return sol}type DummySolution struct { data [100 * 1024 * 1024 * 1024]uint8}func (s *DummySolution) Load() {}func (s *DummySolution) Solve() string { return ""}func Init() { Register(&DummySolution{})}在這個例子中,'DummySolution struct' 的類型是在 Init() 函數中注冊的。為了說明這個問題,這個結構故意大得離譜。有沒有一種方法可以訪問 DummySolution 和其他解決方案的類型而無需事先創建結構實例?
1 回答

海綿寶寶撒
TA貢獻1809條經驗 獲得超8個贊
您可以使用reflect.TypeOf((*DummySolution)(nil)).Elem()
. 創建一個nil
指針不會為整個結構分配空間,并且Elem
(在 的定義下描述reflect.Type
)讓您從一個指針(或切片、數組、通道或映射)到其元素類型。
- 1 回答
- 0 關注
- 214 瀏覽
添加回答
舉報
0/150
提交
取消