首页 > 其他分享 >Go - Using error variables to differentiate between input types

Go - Using error variables to differentiate between input types

时间:2024-06-09 21:44:09浏览次数:22  
标签:err variables invalid arguments error Println input total fmt

 

package main

import (
    "fmt"
    "os"
    "strconv"
)

func main() {
    arguments := os.Args
    if len(arguments) == 1 {
        fmt.Println("Not enough arguments")
    }

    var total, nInts, nFloats int
    var invalid []string
    for _, k := range arguments[1:] {
        // Is it an integer?
        _, err := strconv.Atoi(k)
        if err == nil {
            total++
            nInts++
            continue
        }

        // Is it a float
        _, err = strconv.ParseFloat(k, 64)
        if err == nil {
            total++
            nFloats++
            continue
        }

        // Then it is invalid
        invalid = append(invalid, k)
    }

    fmt.Println("#read:", total, "#ints:", nInts, "#floats:", nFloats)
    if len(invalid) > total {
        fmt.Println("Too much invalid input:", len(invalid))
        for _, s := range invalid {
            fmt.Println(s)
        }
    }
}

 

标签:err,variables,invalid,arguments,error,Println,input,total,fmt
From: https://www.cnblogs.com/zhangzhihui/p/18240051

相关文章