How to dynamically retrieve variables using strings

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

How to dynamically retrieve variables using strings

问题

例如:

type client struct{}
var s := "client"
var b := new(s)  // 获取一个 client 结构体

背景:
有一些变量,如 client_1client_2。现在我尝试通过请求参数 client(作为字符串)来检查 client_x 是否存在。

结果是:

  • client_1 存在
  • client_3 不存在

然后,我可以检索变量 client_1 并使用它。

英文:

Such as:

type client struct{}
var s :="client"
var b := new (s)  //get a struct client

backgroud:
there are variables like client_1, client_2. now I try to check if client_x exists by request parameters:client(as string).

the result is:

  • client_1 exists
  • client_3 does not exists

And then I can retrieve variable client_1 and use it.

答案1

得分: 1

你不能拥有一个类型的map,如果这是你的问题:

package something

// 语法错误:意外的类型,期望类型
var types = make(map[string]type)

但是你可以使用interface{}map,并将每个类型设置为默认值:

package main

var types = map[string]interface{}{"bool": false, "int": 0, "string": "hello"}

func main() {
   s := types["string"]
   t := s.(string)
   println(t == "hello")
}
英文:

You cannot have a map of types, if that's what you're asking:

package something

// syntax error: unexpected type, expecting type
var types = make(map[string]type)

but you could do a map of interface{}, and just set each type to a default
value:

package main

var types = map[string]interface{}{"bool": false, "int": 0, "string": "hello"}

func main() {
   s := types["string"]
   t := s.(string)
   println(t == "hello")
}

答案2

得分: 1

最好的方法是,如果你想通过名称创建一个新类型,你可以将工厂函数放在一个映射中。

type client struct{}
var types = map[string]func()interface{}{
    "client": func() interface{} { return new(client) },
}

类型map[string]func()interface{}表示"从字符串到不带参数并返回interface{}的函数的映射"。

然后,你可以通过名称调用工厂函数:

func main() {
    s := "client"
    b := types[s]()
    _ = b
}

你可以选择interface{}或更具体的接口作为函数的返回类型,但是映射中的所有函数的返回类型必须相同。

英文:

At best, if you want to create a new type by name, you can put factory functions in a map.

type client struct{}
var types = map[string]func()interface{}{
    "client": func() interface{} { return new(client) },
}

The type map[string]func()interface{} is just "a map from strings to functions that take no arguments and return an interface{}".

You can then call the factory function by name:

func main() {
    s := "client"
    b := types
展开收缩
() _ = b }

You can choose interface{} or a more specific interface for the return type of your functions, but the type must be the same for all functions in the map.

huangapple
  • 本文由 发表于 2021年7月19日 09:37:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/68434309.html
匿名

发表评论

匿名网友

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

确定