如何将interface {}转换回其原始结构? [英] How to cast interface{} back into its original struct?

查看:105
本文介绍了如何将interface {}转换回其原始结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种将结构/接口动态转换回其原始对象的方法。
我可以在其中添加方法/函数。基本上我需要这样的东西:

I need a way to dynamically cast a struct/interface back to its original object. I can add methods / functions inside. basically I need something like this:

MyStruct  =>  Interface{}  => MyStruct

在进行最终转换时,我对原始结构一无所知struct,所以我不能这样:

When on the final conversion I don't know anything about the original struct besides what come inside the struct, so I can't just so:

a.(MyStruct)


推荐答案

否:如此线程


Go既不是协变也不是协变。类型不是 等于 ,或者不是。

Go is neither covariant nor contravariant. Types are either equal or they aren't.

您必须将结构拆开并处理碎片,或者使用反射

类型断言仅是 断言 ,而不是任何形式的强制。

You have to either take the structs apart and deal with the pieces, or use reflection.
Type assertions are only "assertions", not "coercions" of any kind.

另请参见此线程,它提醒我们:

See also this thread, which reminds us that:



  • 指针是一种类型。

  • 结构是另一种类型。

  • 整数是另一种类型。

  • 浮点数是另一种类型。

  • 布尔值是另一种类型。

  • A pointer is one kind of type.
  • A struct is another kind of type.
  • An integer is another kind of type.
  • A floating point number is another kind of type.
  • A boolean is another kind of type.

接口的原理涉及类型 T 所附加的方法,而不是类型 T 是。

The principle of an interface concerns the methods attached to a type T, not what type T is.

接口类型由一组方法定义。

可以将实现方法的任何值分配给的接口值。

An interface type is defined by a set of methods.
Any value that implements the methods can be assigned to an interface value of that type.

这将使从接口到具体类型的转换非常困难。

That would make the conversion from interface to concrete type quite difficult to do.

这篇关于如何将interface {}转换回其原始结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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