Convert string to integer type in Go?

前端 未结 5 1975
误落风尘
误落风尘 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:22

    Here are three ways to parse strings into integers, from fastest runtime to slowest:

    1. strconv.ParseInt(...) fastest
    2. strconv.Atoi(...) still very fast
    3. fmt.Sscanf(...) not terribly fast but most flexible

    Here's a benchmark that shows usage and example timing for each function:

    package main
    
    import "fmt"
    import "strconv"
    import "testing"
    
    var num = 123456
    var numstr = "123456"
    
    func BenchmarkStrconvParseInt(b *testing.B) {
      num64 := int64(num)
      for i := 0; i < b.N; i++ {
        x, err := strconv.ParseInt(numstr, 10, 64)
        if x != num64 || err != nil {
          b.Error(err)
        }
      }
    }
    
    func BenchmarkAtoi(b *testing.B) {
      for i := 0; i < b.N; i++ {
        x, err := strconv.Atoi(numstr)
        if x != num || err != nil {
          b.Error(err)
        }
      }
    }
    
    func BenchmarkFmtSscan(b *testing.B) {
      for i := 0; i < b.N; i++ {
        var x int
        n, err := fmt.Sscanf(numstr, "%d", &x)
        if n != 1 || x != num || err != nil {
          b.Error(err)
        }
      }
    }
    

    You can run it by saving as atoi_test.go and running go test -bench=. atoi_test.go.

    goos: darwin
    goarch: amd64
    BenchmarkStrconvParseInt-8      100000000           17.1 ns/op
    BenchmarkAtoi-8                 100000000           19.4 ns/op
    BenchmarkFmtSscan-8               2000000          693   ns/op
    PASS
    ok      command-line-arguments  5.797s
    

提交回复
热议问题