Convert string to integer type in Go?

前端 未结 5 1971
误落风尘
误落风尘 2020-11-30 19:12

I\'m trying to convert a string returned from flag.Arg(n) to an int. What is the idiomatic way to do this in Go?

5条回答
  •  情深已故
    2020-11-30 19:23

    If you control the input data, you can use the mini version

    package main
    
    import (
        "testing"
        "strconv"
    )
    
    func Atoi (s string) int {
        var (
            n uint64
            i int
            v byte
        )   
        for ; i < len(s); i++ {
            d := s[i]
            if '0' <= d && d <= '9' {
                v = d - '0'
            } else if 'a' <= d && d <= 'z' {
                v = d - 'a' + 10
            } else if 'A' <= d && d <= 'Z' {
                v = d - 'A' + 10
            } else {
                n = 0; break        
            }
            n *= uint64(10) 
            n += uint64(v)
        }
        return int(n)
    }
    
    func BenchmarkAtoi(b *testing.B) {
        for i := 0; i < b.N; i++ {
            in := Atoi("9999")
            _ = in
        }   
    }
    
    func BenchmarkStrconvAtoi(b *testing.B) {
        for i := 0; i < b.N; i++ {
            in, _ := strconv.Atoi("9999")
            _ = in
        }   
    }
    

    the fastest option (write your check if necessary). Result :

    Path>go test -bench=. atoi_test.go
    goos: windows
    goarch: amd64
    BenchmarkAtoi-2                 100000000               14.6 ns/op
    BenchmarkStrconvAtoi-2          30000000                51.2 ns/op
    PASS
    ok      path     3.293s
    

提交回复
热议问题