Golang-扫描某种类型的所有结构 [英] Golang - Scan for all structs of type something

查看:86
本文介绍了Golang-扫描某种类型的所有结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Go语言的初学者.我可能认为多年以来其他语言都太传统了,但这就是我想在Go中做的事情.假设以下用例

I am a beginner in Go. I maybe thinking too traditional coming from years in other languages, but here is what I want to do in Go. Assume the following use case

  1. 我有接口I.此接口具有功能start()和stop()
  2. 有许多实现该接口的结构.结构A,结构B,结构C
  3. 应用程序启动时,我想在结构A,B和C上调用start()
  4. 类似地,当应用程序终止时,我想在A,B,C结构上调用stop().
  5. 我不想在代码中的任何地方硬编码结构A,B和C来调用启动/停止功能.这样一来,当我以后添加struct D(也实现接口I)时,代码将自动运行而无需修改.
  6. 为了实现这一目标,我需要能够说嘿,给我实现接口I的所有类型".
  7. 如果我取回A,B和C的一部分,我可以简单地循环遍历并在正确的时间调用正确的方法.

可以在Go中使用吗?

Doable in Go?

推荐答案

简短的答案是:不,那是不可能的

The short answer is: No, that is not doable

Go是严格键入的语言.这样,链接器就可以省去应用程序未使用的类型定义,方法和函数.

Go is a strictly typed language. This allows the linker to leave out type definitions, methods and functions not used by the application.

这意味着,除非在某处引用并使用了某个类型(例如struct A),否则它将被忽略.

That means, unless a type (such as struct A) are referenced and used somewhere, it will be omitted.

但是在您的评论中,您提到您不想要这些类型,而是想要实现接口的任何类型的当前存在的 instances .

But in your comment, you mentioned you don't want the types but rather the currently existing instances of any type that implements the interface.

这也不可能.

替代

我的建议是创建一个全局地图(或切片):

My suggestion is to create a global map (or slice):

var instMap = map[string]StartStopper

并让每个结构体使用init函数将一个实例添加到该映射,该init函数将在应用程序开始时自动被调用:

And have each struct add an instance to that map with an init function that will automatically be called at the start of the application:

type A struct {}

func init() {
    instMap["A"] = new(A)
}

然后,当您要启动所有实例时,只需遍历地图并调用Start()

Then when you want to start all the instances, just iterate over the map and call Start()

修改

如果不是每种类型一个实例,而是每种类型有多个实例,那么每当创建一个新实例时,您都必须将其添加到地图(或切片)中.而且,您将不得不记住当不再使用实例时,将从地图中删除该实例,否则该实例将不会被垃圾收集器处理.

And if it is not a one-instance-per-type situation but rather multiple instances for each type, then you will have to add to the map (or slice) whenever a new instance is created. And you would have to remember deleting the instance from the map when it is not to be used anymore, or else it won't be handled by the Garbage Collector.

这篇关于Golang-扫描某种类型的所有结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆