dongpou7275 2016-02-02 23:12
浏览 42
已采纳

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

I want to create a registry of struct types to enable dynamic loading of solutions to 'Project Euler' problems. My current solution however requires the struct to first be created and zeroed before it's type can be registered:

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
", 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)
", 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{})
}

In this example the type of 'DummySolution struct' is registered inside the Init() function. This structure is purposefully absurdly large to illustrate the problem.

Is there a way I could access the type of DummySolution and other Solutions without having to create an instance of the structure beforehand?

  • 写回答

1条回答 默认 最新

  • dow98764 2016-02-02 23:47
    关注

    You can use reflect.TypeOf((*DummySolution)(nil)).Elem(). Making a nil pointer doesn't allocate space for the whole struct, and Elem (described under the definition of reflect.Type) gets you from a pointer (or slice, array, channel, or map) to its element type.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败