我需要使用Golang重新创建一个Typescript接口。该接口使用[k: string]: any;
键来指示该接口可能具有比接口内部声明的属性更多的属性。
export interface MyInterface {
first: string;
second: string;
[k: string]: any;
}
如何在果朗存档?现在我的结构看起来像这样:
type MyStruct struct {
First string `json:"first"`
Second string `json:"second"`
}
这对两个键都很好,但我怎么能做这样的事情:
var ms MyStruct
ms.First = "first"
ms.Second = "second"
ms.Foo = "bar"
ms.Bar = false
Go是一种静态类型语言,您打算使用的所有字段都必须在编译时声明。
你能做的最接近的事情就是向结构中添加一个映射字段,在其中你可以存储额外的值。
例如:
type MyStruct struct {
First string `json:"first"`
Second string `json:"second"`
Props map[string]interface{} `json:"props"`
}
使用它:
var ms = MyStruct{Props: map[string]interface{}{}}
ms.First = "first"
ms.Second = "second"
ms.Props["Foo"] = "bar"
ms.Props["Bar"] = false
fmt.Println(ms)
哪些输出(在Go Playground上尝试(:
{first second map[Bar:false Foo:bar]}
注意:使用反射(reflect
包(,您可以使用";动态的";字段(在运行时定义(,但仍然不能引用那些字段,就好像它们在编译时定义一样。