如何在不物理创建结构的情况下获取结构的 Reflect.Type 实例?

Jan*_*sis 4 reflection optimization go

我想创建一个结构类型注册表,以动态加载“Project Euler”问题的解决方案。然而,我当前的解决方案要求首先创建结构并将其归零,然后才能注册其类型:

package solution

import (
    "errors"
    "fmt"
    "os"
    "reflect"
)

type Solution interface {
    Load()
    Solve() string
}

type SolutionRegister map[string]reflect.Type

func (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{})
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,“DummySolution struct”的类型在 Init() 函数内注册。为了说明问题,这个结构故意设置得大得离谱。

有没有一种方法可以访问 DummySolution 和其他解决方案的类型,而无需事先创建结构实例?

two*_*two 5

您可以使用reflect.TypeOf((*DummySolution)(nil)).Elem()。创建nil指针不会为整个结构分配空间,并且Elem(在 的定义下进行描述reflect.Type)可以让您从指针(或切片、数组、通道或映射)到其元素类型。