寻找一种优雅的方法来解析一个整数

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

Looking for an elegant way to parse an Integer

问题

现在我正在做以下操作,以从字符串中解析整数,然后将其转换为int类型:

tmpValue, _ := strconv.ParseInt(str, 10, 64) //返回int64
finalValue = int(tmpValue)

这种方法相当冗长,而且不够简洁,因为我还没有找到在ParseInt调用中进行转换的方法。有没有更好的方法来实现这个?

英文:

Right now I am doing the following in order to parse an integer from a string and then convert it to int type:

tmpValue, _ := strconv.ParseInt(str, 10, 64) //returns int64
finalValue = int(tmpValue)

It is quite verbose, and definitely not pretty, since I haven't found a way to do the conversion in the ParseInt call. Is there a nicer way to do that?

答案1

得分: 5

似乎函数strconv.Atoi可以实现你想要的功能,不过它可以在不考虑int位数大小的情况下工作(你的代码似乎假设它是64位宽)。

英文:

It seems that the function strconv.Atoi does what you want, except that it works regardless of the bit size of int (your code seems to assume it's 64 bits wide).

答案2

得分: 3

如果您在程序中只需要写一次,那么我认为没有问题。如果您需要在多个地方使用,您可以编写一个简单的特化包装器,例如:

func parseInt(s string) (int, error) {
        i, err := strconv.ParseInt(str, 10, 32)  // 或者在64位系统上使用64
        return int(i), err
}

标准库的目标不是为每种可能的数字类型和/或它们的组合提供(臃肿的)API。

英文:

If you have to write that once in your program than I see no problem. If you need at several places you can write a simple specialization wrapper, for example:

func parseInt(s string) (int, error) {
        i, err := strconv.ParseInt(str, 10, 32)  // or 64 on 64bit tip
        return int(i), err
}

The standard library doesn't aim to supply (bloated) APIs for every possible numeric type and/or their combinations.

答案3

得分: 2

不要忘记检查错误。例如,

package main

import (
	"fmt"
	"strconv"
)

func main() {
	s := "123"
	i, err := strconv.Atoi(s)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(i)
}

输出:

123
英文:

Don't forget to check for errors. For example,

package main

import (
	"fmt"
	"strconv"
)

func main() {
	s := "123"
	i, err := strconv.Atoi(s)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(i)
}

Output:

123

huangapple
  • 本文由 发表于 2012年12月16日 21:07:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/13901566.html
匿名

发表评论

匿名网友

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

确定