首页 > 解决方案 > 结构数组,包括在 Go 中选择时调用的函数

问题描述

我对 Go 很陌生,对如何实现这一点有点困惑:

我正在使用 promptui 为用户提供可供选择的选项列表。选择时,我想为每个选项分配一个函数 - 被调用所选项目的功能。

最接近的实现示例是这个,在他们的文档中:https ://github.com/manifoldco/promptui/blob/master/_examples/custom_select/main.go

任何帮助将非常感激。谢谢!

标签: 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)

...

顺便说一句,它是结构值的一部分,而不是数组。


推荐阅读