go - 结构数组,包括在 Go 中选择时调用的函数
问题描述
我对 Go 很陌生,对如何实现这一点有点困惑:
我正在使用 promptui 为用户提供可供选择的选项列表。选择时,我想为每个选项分配一个函数 - 被调用所选项目的功能。
最接近的实现示例是这个,在他们的文档中:https ://github.com/manifoldco/promptui/blob/master/_examples/custom_select/main.go
任何帮助将非常感激。谢谢!
解决方案
在结构中添加一个函数字段并初始化:
type pepper struct {
Name string
HeatUnit int
Peppers int
fn func() // add arguments and return values as a needed.
}
peppers := []pepper{
{Name: "Bell Pepper", HeatUnit: 0, Peppers: 0, fn: func() { fmt.Println("Bell") }},
...
}
选择后调用函数:
...
peppers[i].fn() // call function
fmt.Printf("You choose number %d: %s\n", i+1, peppers[i].Name)
...
顺便说一句,它是结构值的一部分,而不是数组。
推荐阅读
- python - TKinter。每 10 秒刷新一次从 csv 获取的变量
- load - 在 q kdb 中检索展开的表
- java - 如何序列化字节数组以作为 HTTP POST 的正文发送?
- angular - 在 WebStorm 中设置 AWS Amplify GraphQL API 时出现“未知指令模型”
- mysql - 订购方式
可以用吗? - python - python中的for循环帮助
- libreoffice - Libre office Calc 和 Hour 持续时间格式?
- ruby-on-rails - 复制控制器类实例变量
- prometheus - 将 influx stddev 翻译成 promQL
- c# - JSON字符串中特定位置的属性/值的JSON路径