Golang var关键字和short声明操作符的区别

Golang var关键字和short声明操作符的区别

变量是一个用于保存数值的存储位置或放置器。它允许我们操作和检索存储的信息。在Golang中,有两种声明变量的方法,如下所示。

  • 使用var关键字
  • 使用简短的声明操作符 ( := )

var关键字和短声明操作符的区别

var关键字 short声明操作符
var是Golang中存在的一个词法关键字。 :=被称为短声明操作符。
它用于声明和初始化函数内部和外部的变量。 它只用于在函数内部声明和初始化变量。
使用它,变量通常具有包级或全局级范围。它也可以有局部范围。 在这里,变量只有局部范围,因为它们只在函数内部声明。
变量的声明和初始化可以分开进行。 变量的声明和初始化必须在同一时间进行。
在声明变量的同时,可以选择输入类型。 没有必要输入类型。如果你这样做,就会产生错误。

例1: 在这个程序中,你可以看到myvariable1是用var关键字声明的,它有局部范围。myvariable2也是用var关键字声明的,类型是int,但没有做初始化。myvariable3是用short变量声明操作符声明和初始化的,它有局部范围。

// Go program to show the use of var lexical 
// keyword and short declaration operator
package main
  
import (
    "fmt"
)
  
func main() {
  
// using var keyword to declare 
// and initialize the variable
var myvariable1 = 100
  
fmt.Println(myvariable1)
  
// using var keyword to declare 
// the variable along with type
var myvariable2 int
  
fmt.Println(myvariable2)
  
// using short variable declaration
myvariable3 := 200
  
fmt.Println(myvariable3)
      
}
Go

输出

100
0
200
Go

例2: 在这个程序中,你可以看到myvariable1是用var关键字声明的,它有全局范围。myvariable2也是用var关键字声明的,它的类型是int,但没有做初始化。myvariable3是用short变量声明操作符声明和初始化的,它有局部作用域,所以它将采用int类型的默认值,即0(你可以在输出中看到)。

// Go program to show the use of var lexical 
// keyword and short declaration operator
package main
  
import (
    "fmt"
)
  
// using var keyword to declare 
// and initialize the variable
// it is package or you can say 
// global level scope
var myvariable1 = 100
  
func main() {
  
// accessing myvariable1 inside the function
fmt.Println(myvariable1)
  
// using var keyword to declare 
// the variable along with type
var myvariable2 int
  
fmt.Println(myvariable2)
  
// using short variable declaration
myvariable3 := 200
  
fmt.Println(myvariable3)
      
}
Go

输出

100
0
200
Go

例3: 在这个程序中,你可以看到myvariable1是用var关键字声明的,它有全局范围。myvariable2也是用var关键字声明的,它的类型是int,但没有做初始化。myvariable3是在函数外使用短变量声明操作符声明和初始化的,这是不允许的,因此出现了错误。

// Go program to show the use of var lexical 
// keyword and short declaration operator
package main
  
import (
    "fmt"
)
  
// using var keyword to declare 
// and initialize the variable
// it is package or you can say 
// global level scope
var myvariable1 = 100
  
// using short variable declaration
// it will give an error as it is not 
// allowed outside the function
myvariable3 := 200
  
func main() {
  
// accessing myvariable1 inside the function
fmt.Println(myvariable1)
  
// using var keyword to declare 
// the variable along with type
var myvariable2 int
  
fmt.Println(myvariable2)
  
  
fmt.Println(myvariable3)
      
}
Go

错误

./prog.go:18:1: 语法错误:函数体外的非声明语句

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册