字符串转换为整数的类型转换

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

Type conversion of string to int

问题

好的,以下是翻译的部分:

我一直在处理将字符串转换为字节写入的类型转换问题。这是编译器错误:

无法将row[5](类型为uint8)作为字符串类型的函数参数使用

无法将&v(类型为*Field)作为整数类型的函数参数使用

这是row[5]的一个示例:$15,000.00

我声明了一个结构体:

type Field struct {
Eia uint8
}

以下是主要实现部分:

for {
	record, err := reader.Read()
	if err == io.EOF {
		break
	} else if err != nil {
		panic(err)
	}

	var v Field
	for _, row := range record {
		eia, err := strconv.ParseInt(row[5], 8, &v) // 估计的进账金额
		if err == nil {
			fmt.Printf("%+v\n", v)
		} else {
			fmt.Println(err)
			fmt.Printf("%+v\n", v)
		}

请问有人可以解释一下strconv如何将row转换为整数吗?

英文:

Ok, so I've been having difficulties with the type conversion of a string to byte write. This is the compiler error:

> cannot use row[5] (type uint8) as type string in function argument

> cannot use &v (type *Field) as type int in function argument

This is an example of row[5]: $15,000.00

Ive declared a struct:

type Field struct {
Eia uint8
}

here is the main implementation:

for {
	record, err := reader.Read()
	if err == io.EOF {
		break
	} else if err != nil {
		panic(err)
	}

	var v Field
	for _, row := range record {
		eia, err := strconv.ParseInt(row[5], 8, &v) // Estimated Incoming Amount
		if err == nil {
			fmt.Printf("%+v\n", v)
		} else {
			fmt.Println(err)
			fmt.Printf("%+v\n", v)
		}

Can anyone please explain to me how strconv can convert the row to a integer?

答案1

得分: 3

如果你在http://play.golang.org/上创建一个完整的示例,那么给你一个完整的解决方案会更容易。

ParseInt()接受一个字符串(你可能需要做string(row[5])),基数(你可能指的是10)和位大小(这是你应该放入8的地方)。

它返回一个int(eia),它不会将其放入结构体中,因为你似乎正在尝试。

而是做if err == nil { v.Eia = eia }

英文:

If you made a complete example on http://play.golang.org/ it'd be easier to give you a complete solution.

ParseInt() takes the string (you might have to do string(row[5])), the base (you probably meant 10) and the bitsize (that's where you should put 8).

It retuns an int (eia), it doesn't put it into the struct as it looks like you are trying.

Instead do if err == nil { v.Eia = eia }.

huangapple
  • 本文由 发表于 2013年3月26日 04:44:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/15624402.html
匿名

发表评论

匿名网友

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

确定