We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
GO中的constant与类C语言中的不太一样。
在C中,我们可以对不同类型的变量进行运算,譬如:int 与 uint 可以加减。但在Go中,禁止了这么做(认为会带来更多的bugs),不同类型的变量不能进行操作,除非通过显示的类型转换。
说回constant,在go里,constant就是一个非常简单的,不可改变的值。或者说,在 compile time 就能够确定的。
const hello = "Hello, 世界",这里,常量hello没有明确的类型,它属于untyped string constant。一方面:当我们执行str := "Hello, 世界",常量hello虽没有明确的类型,但是有一个隐式的默认类型(这个默认类型是通过语法来辨别的),所以我们可以确定str的类型是string;另一方面,正因为它是untyped,所以它避免了GO的强制类型检查
const hello = "Hello, 世界"
str := "Hello, 世界"
The text was updated successfully, but these errors were encountered:
总的来说:golang里严格要求两个有类型变量操作时类型一致。但是又为了一定程度的方便(无需对常量也显式类型转换),允许untyped constant,但它会有一个根据语法得到的隐式的默认类型。
此外,当我们将一个untyped constant赋值给一个T类型变量时,只要这个constant的值可以用类型T来表示,也可以直接赋值成功。
Sorry, something went wrong.
An exercise: The largest unsigned int
1.uint不等于uint32(同理float),uint会根据当前机器的架构来决定占用位数。所以不能硬编码1<<32 - 1
1<<32 - 1
2.正确的做法:const MaxUint = ^uint(0),利用补码性质和位取反
const MaxUint = ^uint(0)
PS:golang里的位取反是^,而不是C里的~
No branches or pull requests
GO中的constant与类C语言中的不太一样。
在C中,我们可以对不同类型的变量进行运算,譬如:int 与 uint 可以加减。但在Go中,禁止了这么做(认为会带来更多的bugs),不同类型的变量不能进行操作,除非通过显示的类型转换。
说回constant,在go里,constant就是一个非常简单的,不可改变的值。或者说,在 compile time 就能够确定的。
const hello = "Hello, 世界"
,这里,常量hello没有明确的类型,它属于untyped string constant。一方面:当我们执行str := "Hello, 世界"
,常量hello虽没有明确的类型,但是有一个隐式的默认类型(这个默认类型是通过语法来辨别的),所以我们可以确定str的类型是string;另一方面,正因为它是untyped,所以它避免了GO的强制类型检查The text was updated successfully, but these errors were encountered: