Activator.CreateInstance() analogue in Golang

huangapple go评论86阅读模式
英文:

Activator.CreateInstance() analogue in Golang

问题

在Go编程语言中,可以使用反射来实现类似的功能。Go语言中的反射包reflect提供了一些方法来创建类型的实例。你可以使用reflect.New()函数来创建一个指向类型的指针,并使用Elem()方法获取指针指向的值。下面是一个示例代码:

package main

import (
	"fmt"
	"reflect"
)

func main() {
	// 获取类型
	typeName := "YourTypeName"
	typeValue := reflect.TypeOf(typeName)

	// 创建实例
	instance := reflect.New(typeValue).Elem()

	// 打印实例
	fmt.Println(instance)
}

你需要将YourTypeName替换为你要创建实例的类型名称。这段代码将创建一个指向该类型的指针,并使用Elem()方法获取指针指向的值,即类型的实例。

请注意,Go语言中的反射功能相对较为底层,使用时需要谨慎处理类型匹配和错误处理。

英文:

In C#, there's a method CreateInstance of class Activator which allows you to create an instance of the reflected type as it is shown here.

Is there a way to do the same tihing in Go programming language? I would like to take a type from a plugin (.so on Linux or .dll on Windows) by the name of the type and create an instance of this type in my code. How can I do that?

答案1

得分: 2

> 在Go编程语言中有没有一种方法可以做到同样的事情?

没有。

> 我想通过类型的名称从插件(在Linux上是.so文件,在Windows上是.dll文件)中获取一个类型,并在我的代码中创建该类型的实例。我该如何做到这一点?

你不能这样做。抱歉。你必须重新设计。Go不是C#,有不同的规则。其中一个规则是你不能仅凭类型的名称来创建实例。但是,如果你的插件通过某种注册表(类似于包image)宣布它包含的类型及其名称,那么你的主要代码可以在该注册表中查找名称和类型,并进行正常的反射。

英文:

> Is there a way to do the same tihing in Go programming language?

No.

> I would like to take a type from a plugin (.so on Linux or .dll on Windows) by the name of the type and create an instance of this type in my code. How can I do that?

You cannot. Sorry. You must redesign. Go is not C# and has different rules. One rule is that you can't create instances of types by their name alone. But if your plugin announces which types it contains and their names via some kind of registry (think of package image) then your main code can look up names and types in that registry and reflect normally.

huangapple
  • 本文由 发表于 2021年6月1日 02:35:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/67778780.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定