在Go语言中进行输入验证

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

Input validation in golang

问题

这是我的代码片段,我不知道如何验证number1和number2变量的输入数据类型。我希望它们是float64类型的数字,而不是字符串或其他类型。我已经了解了try catch,但我不知道如何在这里使用它们。或者有没有更简单的验证方法?

package main

import (
	"fmt"
	"math"
)

func main() {
	var number1, number2 float64
	var operator string

	fmt.Print("Enter the first number: ")
	fmt.Scanln(&number1)

	fmt.Print("Enter the second number: ")
	fmt.Scanln(&number2)

	fmt.Print("Enter the operator +, -, *, /, **: ")
	fmt.Scanln(&operator)
英文:

Here is my code snippet and i dont know how to validate input data type in number1 and number2 variables. I need them to be float64 digits but not a string or other type. I've read about try catch, but I don't know how to use them here. Or is there an easier way of validation?

package main

import (
	"fmt"
	"math"
)

func main() {
	var number1, number2 float64
	var operator string

fmt.Print("Enter the first number: ")
fmt.Scanln(&number1)

fmt.Print("Enter the second number: ")
fmt.Scanln(&number2)

fmt.Print("Enter the operator +, -, *, /, **: ")
fmt.Scanln(&operator)

答案1

得分: 0

你可以使用strconv.ParseFloat函数来检查一个字符串值是否是一个正确的float64类型。

f, err := strconv.ParseFloat("4.56", 64)
if err != nil {
    fmt.Println("该值不是一个有效的浮点数!")
    return
}
fmt.Print(f)

请注意,以上代码是Go语言的代码示例。

英文:

You can check if a string value is a correct float64 using the strconf.ParseFloat function

f, err := strconv.ParseFloat("4.56", 64)
if err != nil {
	fmt.Println("The value is not a valid float!")
	return
}
fmt.Print(f)

huangapple
  • 本文由 发表于 2022年10月14日 16:54:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/74066742.html
匿名

发表评论

匿名网友

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

确定