[Easy to understand series | golang language | zero-based | Getting Started | (d)]

Today, we have to write code.

Learning a language, the fastest way is to write code to do the project.

Other tutorials are hello world.

 We come to something different now. We are not the same! Different! Different!

First, open VSCODE (about VSCODE configuration, see: https: //www.jianshu.com/p/83beca927c9e,https: //zhuanlan.zhihu.com/p/59879132).

write the code:

package main

where  x,  int
var (   // this factorization general wording keyword is used to declare global variables
    int
    bool
)

var  c,  you  = 1, 2
var e, = 123, "hello"

// This format without a declaration can only appear in the body of the function
//g, h := 123, "hello"

func main(){
    g, := 123, "hello"
    println (x, y, a, b, c, d, e, f, g, h)
}
 
The output is:
0 0 0 false 1 2 123 hello 123 hello

Let them out:

1) where  x,  int

这里通过var关键词,来定义变量 x,y,并且golang自动赋值为0.所以结果打印都为:0

 

2)var (  

 

    int

 

    bool

 

)
这种声明方式,一般用在全局变量。其中bool为布尔值,默认值为:false.
 
 3)var c, int = 1, 2
golang可以定义多个变量的类型,并为变量赋值。
 
4)var e, = 123, "hello"
golang也可以对不同类型的变量,同时赋值,并自动推导类型,这个就是:编译器推导类型的格式。
 
var 的变量声明还有一种更为精简的写法,例如:
  1. hp := 100
这是Go语言的推导声明写法,编译器会自动根据右值类型推断出左值的对应类型。

注意:由于使用了:=,而不是赋值的=,因此推导声明写法的左值变量必须是没有定义过的变量。若定义过,将会发生编译错误。

5)g, := 123, "hello"
 
这种不带声明格式的只能在函数体中出现
 
短变量声明的形式在开发中的例子较多,比如:
  1. conn, err := net.Dial("tcp","127.0.0.1:8080")
net.Dial 提供按指定协议和地址发起网络连接,这个函数有两个返回值,一个是连接对象(conn),一个是错误对象(err)。如果是标准格式将会变成:
  1. var conn net.Conn
  2. var err error
  3. conn, err = net.Dial("tcp", "127.0.0.1:8080")
因此,短变量声明并初始化的格式在开发中使用比较普遍。

注意:在多个短变量声明和赋值中,至少有一个新声明的变量出现在左值中,即便其他变量名可能是重复声明的,编译器也不会报错,代码如下:
  1. conn, err := net.Dial("tcp", "127.0.0.1:8080")
  2. conn2, err := net.Dial("tcp", "127.0.0.1:8080")
上面的代码片段,编译器不会报 err 重复定义。
 
以上代码,全部可运行。建议用IDE写代码并运行。
 

Guess you like

Origin www.cnblogs.com/gyc567/p/11875271.html