go语言变量声明很简单,常见有以下几种:
1.常规变量声明
var power0 int power0 = 900
这是标准声明模式,也是最冗长的,例如上面声明的 power0 变量。
2.简写模式
power := 9001 fmt.Printf("It's power is over %d\n", power)
该模式较为简洁,即声明了 power变量并赋值9001,这种模式会自动识别变量类型,不过该模式只能声明局部变量,全局变量则不可以使用。
3.函数式简写
func getPower() int { return 9002 } power2 := getPower() fmt.Printf("It's power is over %d\n", power2)
该模式与函数结合,非常方便。
该模式需要注意相同的函数不能被声明两次,如果这样使用即会提示编译器错误。
4.多变量赋值
name, power3 := "JueJin", 90003 fmt.Printf("%s's power is over %d\n", name, power3)
该模式同时给多个变量赋值,同时只需要有一个是新变量即可,不会报错。
此外需要注意的是,go语言中,未使用的变量不可以存在,否则会报语法错误,导致编译失败,这样可以有助于提高代码清洁度和可读性。
5.代码
代码
package main import ( "fmt" ) func getPower() int { return 9002 } func main() { var power0 int power0 = 9000 fmt.Printf("It's power is over %d\n", power0) power1 := 9001 fmt.Printf("It's power is over %d\n", power1) power2 := getPower() fmt.Printf("It's power is over %d\n", power2) name, power3 := "JueJin", 90003 fmt.Printf("%s's power is over %d\n", name, power3) }
F5一件运行,输出如下
Starting: C:\Users\livingbody\go\bin\dlv.exe dap --check-go-version=false --listen=127.0.0.1:1820 from c:\Users\livingbody\goworkspace\hello DAP server listening at: 127.0.0.1:1820 Type 'dlv help' for list of commands. It's power is over 9000 It's power is over 9001 It's power is over 9002 JueJin's power is over 90003 Process 8008 has exited with status 0 Detaching dlv dap (19948) exited with code: 0