在Go语言中,如何验证用户输入的数据类型与代码中的数据类型匹配?

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

In Go, how to verify that the data type of an input from the user matches the data type of the code?

问题

我是新手学习Go语言。

目前,我正在使用Go创建一个菜单,并且我想验证用户输入的数据类型是否与代码中定义的变量的数据类型匹配。到目前为止,我的代码部分如下所示:

package main
import (
	"fmt"
	"reflect"
)

var option int // 变量在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
	}
} // 如果从int转换为字符串是可能的,即输入的值是字符串,则此函数返回一个true布尔值。
英文:

I am new to Go.

Currently, I am creating a menu in Go and I want to verify that the data type of the input from the user matches the data type of the variable defined in the code. Part of my code looks like this so far:

package main
import (
	"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()
		}
}

I know that this doens't work this way, and I know that "int" can not be used as part of an "if" condirion.

I would kindly appreciate any suggestions on the proper way to solve this problem.

Thanks.

Edit: I have added more of my code as kindly suggested by the contributors.

Edit: Based on the answer provided, I have tried to implement a function, but the syntax is still not correct:

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.

答案1

得分: 2

只需阅读Scan的文档-https://pkg.go.dev/fmt#Scan

它返回成功读取的参数数量和一个错误。在你的情况下,输入被映射到一个int类型的变量,所以如果用户输入一个字符串,它将返回0和一个错误。否则,它将返回1,错误应该为nil。你可以检查这一点。

n, err := fmt.Scan(&option)
if n != 1 || err != nil {
  // 打印错误并返回
}
英文:

Just read the documentation of Scan - https://pkg.go.dev/fmt#Scan

It returns the number of successfully read arguments and an error. The input is mapped in your case to a variable of type int, so if a user inputs a string it will return 0 and an error. Otherwise it will return 1 and the error should be nil. You can check for that.

n, err := fmt.Scan(&option)
if n != 1 || err != nil {
  // print error and go back 
}

答案2

得分: 1

一种常见的方法是尝试进行转换并查看是否成功。

optionInt, err := strconv.Atoi(option) // 假设 option 的类型为 string
if err != nil {
    log.Printf("无法将字符串 '%s' 转换为 int 类型:%v", option, err)
    os.Exit(1)
}
log.Printf("optionInt 的值为 %d。", optionInt)

如果你只对转换为一种类型感兴趣,这是一个不错的方法。否则,事情可能会变得更加复杂,需要使用词法分析器和解析器等构造,但这需要更多关于你想要实现的内容的信息。

英文:

One common way to do it is to try to make the conversion and see if it succeeds.

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)

This is a good approach if you are only interested in conversion to one type. Otherwise things can quickly get more involved, utilizing constructs such as lexers and parsers, but that would warrant more information on what you are trying to accomplish.

huangapple
  • 本文由 发表于 2022年1月20日 03:23:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/70776602.html
匿名

发表评论

匿名网友

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

确定