AlecAivazis / survey

A golang library for building interactive and accessible prompts with full support for windows and posix terminals.
MIT License
4.08k stars 351 forks source link

[Bug] #331

Closed brenley closed 3 years ago

brenley commented 3 years ago

Using Transform option with Select and returning another interface causes Cleanup to panic.

e.g. given:

err := survey.Ask([]*survey.Question{{
        Name: "FavoriteFruit",
        Prompt: &survey.Select{
            Message: "What is your favorite fruit?",
            Default: "banana",
            Options: []string{"apple", "banana", "grape"},
        },
        Transform: func(ans interface{}) interface{} {
            switch ans := ans.(type) {
            case core.OptionAnswer:
                return FruitFromString(ans.Value)
            }
            return nil
        },
    },
}}, &surveyData)

https://github.com/AlecAivazis/survey/blob/e64d9b644fb7d85d69cd3e33a92a43ee706c1b6f/select.go#L323

panic: interface conversion: interface {} is Fruit, not core.OptionAnswer

goroutine 1 [running]:
github.com/AlecAivazis/survey/v2.(*Select).Cleanup(0xc000446240, 0xc0003f2468, 0x1ab1240, 0xc00040cc38, 0x1, 0xc000428238)
AlecAivazis commented 3 years ago

Hey @brenley!

Let me start by admitting this part of the API is slightly confusing. The issue you are running into is caused by your return value in Transform. The Transform of a Select prompt can return string, int, or survey.OptionAnswer.

Unfortunately, this forces you to serialize and deserialize the struct you want but at the moment that's how things are structured. For more information on this you can see #105