int data type in Go

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

int data type in Go

问题

我是新手学习Go语言,并尝试在Go中运行一些示例代码。

在Go中,int不是一个关键字,所以我声明了一个名为int的变量。

package main
import "fmt"

func main() {
    var int int = 8
    fmt.Println(int)

    var number int = 10
    fmt.Println(number)
}

当我构建这段代码时,我得到以下错误:

[dev@go test]$ go build variables.go
# command-line-arguments
./variables.go:8: int is not a type

我试图理解为什么会出现这个错误,以及var int int是如何使int成为一个不可用的数据类型的。

英文:

I am new to Go language and was trying out few examples in GO.
In GO int is not a keyword so I declared a variable with name as int.

package main
import "fmt"

func main() {
    var int int = 8
    fmt.Println(int)

    var number int = 10
    fmt.Println(number)
}

Now when I build this code I get following error:

[dev@go test]$ go build variables.go
# command-line-arguments
./variables.go:8: int is not a type

I am trying to understand the reason why this is seen and what did var int int do such that int becomes an unavailable data type.

答案1

得分: 3

包 main

import "fmt"

func main() {
// int 是预声明的类型标识符
var int int = 8
// int 是变量标识符
fmt.Println(int)

// 错误:int 不是一个类型
var number int = 10
fmt.Println(number)

}

你正在遮蔽 int 标识符。

参见 Go 编程语言规范

Go 是一种块结构化的编程语言:

声明和作用域

int 是一个预声明的标识符,并且在全局作用域中隐式声明。

在函数内部声明的变量标识符的作用域从声明的末尾开始,到最内层的包含块的末尾结束。

语句

var int int = 8

使用预声明的 int 类型来声明一个变量标识符 int,遮蔽了预声明的标识符:变量遮蔽

英文:
package main

import "fmt"

func main() {
	// int is a predeclared type identifier
	var int int = 8
	// int is a variable identifier
	fmt.Println(int)

	// error: int is not a type
	var number int = 10
	fmt.Println(number)
}

You are shadowing the int identifier.

See The Go Programming Language Specification.

Go is a block structured programming language:

Blocks

Declarations and scope

int is a predeclared identifier and is implicitly declared in the universe block.

The scope of a variable identifier declared inside a function begins at the end of the declaration and ends at the end of the innermost containing block.

The statement

var int int = 8

uses the predeclared int type to declare a variable identifier int, shadowing the predeclared identifier: Variable shadowing.

答案2

得分: 0

在Go语言中,int是一个预定义的标识符,因此不能用作变量名。所以将第一个变量重命名为其他任何名称,比如num1,它就可以编译通过了!

package main
import "fmt"

func main() {
    var num1 int = 8
    fmt.Println(num1)

    var number int = 10
    fmt.Println(number)
}

希望这可以帮到你!

英文:

In Go int is a predefined identifier, therefore it cannot be used as a variable name. So rename the first variable to anything else. Such as num1 and it will compile!

package main
import "fmt"

func main() {
    var num1 int = 8
    fmt.Println(num1)

    var number int = 10
    fmt.Println(number)
}

Hope this helps!

huangapple
  • 本文由 发表于 2017年8月23日 18:05:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/45836683.html
匿名

发表评论

匿名网友

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

确定