我是 Go 新手。目前,我正在 Go 中创建一个菜单,我想验证用户输入的数据类型是否与代码中定义的变量的数据类型相匹配。到目前为止,我的部分代码如下所示:package mainimport ( "fmt" "reflect")var option int // The variable is declared outside of the main().func general_menu() { fmt.Println(".......................General Menu..................................") fmt.Println() fmt.Println("Calculator..........................................................1") fmt.Println("Linear algebra package..............................................2") fmt.Println("Language change.....................................................9") fmt.Println("Exit...............................................................10") fmt.Println() fmt.Println("Choose an option from the menu.") fmt.Println() fmt.Scan(&option) fmt.Println() if (option != 1 && option != 2 && option != 9 && option != 10)||reflect.TypeOf(option)!=int{ fmt.Println("Wrong option input. Please, try again.") fmt.Println() general_menu() }}我知道这不起作用,而且我知道“int”不能用作“if”条件的一部分。对于解决此问题的正确方法的任何建议,我将不胜感激。谢谢。编辑:根据贡献者的建议,我添加了更多代码。编辑:根据提供的答案,我尝试实现一个函数,但语法仍然不正确:func check_integers_are_not_string(x int) bool { change := strconv.Itoa(x) if change != nil { return true } else { return false }} // This function returns a true boolean value if conversion from int to string was possible, meaning that the entered value is a string.
2 回答

函数式编程
TA贡献1807条经验 获得超9个赞
只需阅读 Scan 的文档 - https://pkg.go.dev/fmt#Scan
它返回成功读取参数的数量和一个错误。在您的情况下,输入被映射到一个 int 类型的变量,因此如果用户输入一个字符串,它将返回 0 和一个错误。否则它将返回 1 并且错误应该为零。你可以检查一下。
n, err := fmt.Scan(&option)
if n != 1 || err != nil {
// print error and go back
}

跃然一笑
TA贡献1826条经验 获得超6个赞
一种常见的方法是尝试进行转换并查看它是否成功。
optionInt, err := strconv.Atoi(option) // Assuming option is of type string
if err != nil {
log.Printf("String '%s' cannot be converted to type int: %v", option, err)
os.Exit(1)
}
log.Printf(`optionInt is %d.`, optionInt)
如果您只对转换为一种类型感兴趣,这是一种很好的方法。否则,事情可能很快就会变得更加复杂,使用诸如词法分析器和解析器之类的结构,但这将保证更多关于您正在尝试完成的信息的信息。
- 2 回答
- 0 关注
- 154 浏览
添加回答
举报
0/150
提交
取消