为什么数字01000会转换成512?

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

Why does the number 01000 convert to 512?

问题

我几天前开始学习Go语言,在学习关于structs的时候,我遇到了一个问题。我想创建一个联系人结构体,但是终端上打印出来的邮政编码是512,而不是01000。

以下是代码块:

package main

import "fmt"

type contactInfo struct {
	email   string
	zipCode int
}

type person struct {
	firstName string
	lastName  string
	contact   contactInfo
}

func main() {
	jim := person{
		firstName: "Jim",
		lastName:  "Party",
		contact:   contactInfo{email: "jim.party@gmail.com", zipCode: 01000},
	}

	fmt.Printf("%+v", jim)
}

以下是终端的输出:

{firstName:Jim lastName:Party contact:{email:jim.party@gmail.com zipCode:512}}%

我使用了go run main.go命令,期望的邮政编码是01000,但是得到的是512。

英文:

I started to learn Go a few days ago and while learning about structs I came across and instance where I wanted to create a contacts structure and the zip code of 01000 was printed to the terminal as 512 instead on 01000

Here is the block of code:

package main

import "fmt"

type contactInfo struct {
	email   string
	zipCode int
}

type person struct {
	firstName string
	lastName  string
	contact   contactInfo
}

func main() {
	jim := person{
		firstName: "Jim",
		lastName:  "Party",
		contact:   contactInfo{email: "jim.party@gmail.com", zipCode: 01000},
	}

	fmt.Printf("%+v", jim)
}

Here is the output to the terminal :

{firstName:Jim lastName:Party contact:{email:jim.party@gmail.com zipCode:512}}%  

I used the command go run main.go and was expecting 01000 as the zip code but I got 512.

答案1

得分: 7

因为0前缀表示八进制。我们可以在Go规范中了解到这一点:

octal_lit      = "0" [ "o" | "O" ] [ "_" ] octal_digits .

因此,字面字符串01000被解释为1 * 8^3 + 0 * 8^2 + 0 * 8^1 + 0 * 8^0 = 512。

截至Go 1.13,当你打算使用八进制时,你可以(而且可能应该)使用0o的约定,而不是0,以提高可读性。也就是说,最好写成0o1000,因为这样更加视觉上独特和清晰地表明了意图是使用八进制。


在你的特定情况下,你应该将邮政编码视为字符串,而不是数字。

英文:

Because the 0 prefix indicates octal. We can read about this in Go spec:

> ebnf
> octal_lit = "0" [ "o" | "O" ] [ "_" ] octal_digits .
>

So the literal string 01000 is interpreted as 1 * 8^3 + 0 * 8^2 + 0 * 8^1 + 0 * 8^0 = 512.

As of Go 1.13, you can (and probably "should") use the convention of 0o instead of 0, when you intend to use octal, for improved readability. That is to say, it would be better to write 0o1000, as that is more visually distinct and clear that octal was intended.

<hr>

In your specific case, you should treat zip codes as strings, not as numbers.

huangapple
  • 本文由 发表于 2023年7月5日 15:39:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76618096.html
匿名

发表评论

匿名网友

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

确定