Go语言基础(二)变量,常量以及与其他语言的差异 电脑版发表于:2020/5/23 15:17 ![go语言基础一](https://img.tnblog.net/arcimg/hb/0dd243ae49394f12beed84237bfee1a3.jpg "go语言基础一") >#Go语言基础(二)变量,常量以及与其他语言的差异 [TOC] <br/> 编写测试程序 ------------ <br/> >###注意事项 1. 源码文件以_test结尾:xxx_test.go 2. 测试方法名以Test开头:func Testxxx(t *testing.T){...} >###编写简单的测试代码 <br/> >first_test.go ```go package try_test import ( "testing" ) func TestFirstTry(t *testing.T) { t.Log("My first try") //测试日志输出 t.Error("Over") //测试问题输出 } ``` >结果 ![结果](https://img.tnblog.net/arcimg/hb/1e4643ee8de943e4bf091c68199be0cc.png "结果") <br/> 实现 Fibonacci 数列 (变量) ------------ <br/> >###举例 1,1,2,3,5,8,13... >###编写内容 ```go package fib import "testing" func TestFibList(t *testing.T) { var a int = 1 var b int = 1 t.Log("", b) for i := 0; i < 5; i++ { t.Log(" ", b) tem := a a = b b = tem + a } t.Error("Over") } ``` >###运行结果 ![运行结果](https://img.tnblog.net/arcimg/hb/9c84353565c44d16a6e5acc5b5d8b8a5.png "运行结果") >###简化声明方式 <br/> >简化一 >在一个赋值语句中可以对多个变量进行同时赋值 ```go var ( a int = 1 b int = 1 ) ``` >简化二 >赋值可以进行自动类型判断 ```go a := 1 b := 1 ``` >###全局声明 <br/> >在方法外声明 a 变量 ```go var a int func TestFibList(t *testing.T) { ... a=1 ... } ``` >###简化中间变量赋值 >定义 TestExchange 方法 ```go func TestExchange(t *testing.T) { a := 1 b := 2 a, b = b, a t.Log(a, b) t.Error("Over") } ``` >结果 ![结果](https://img.tnblog.net/arcimg/hb/eb4cbd586b4044d7bc38a3d6ea2febc2.png "结果") <br/> 常量定义 ------------ <br/> >###连续设置连续值 <br/> >const_test.go ```go package const_test import "testing" const ( Monday = 1 + iota Tuesday Wednesday Thursday Friday Saturday Sunday ) func TestConst(t *testing.T) { t.Log(Monday, Tuesday, Wednesday) t.Error("Over") } ``` >结果 ![结果](https://img.tnblog.net/arcimg/hb/2b04293684d04710ad6f0f260470d526.png "结果") >###位运算的常量定义 <br/> >代码定义 ```go const ( Readable = 1 << iota //0001 Writable //0010 Executable //0100 Firable //1000 ) func TestConst(t *testing.T) { t.Log(Readable, Writable, Executable, Firable) t.Error("Over") } ``` >结果 ![结果](https://img.tnblog.net/arcimg/hb/b85af9df1b914e688362b5e5a37d5109.png "结果") >###位运算 <br/> >代码内容 ```go func TestConstantTry(t *testing.T) { a := 7 //0111 t.Log(Readable, Writable, Executable, Firable) t.Log(a&Readable, a&Writable, a&Executable, a&Firable) t.Log(a&Readable == Readable, a&Writable == Writable, a&Executable == Executable, a&Firable == Firable) t.Error("Over") } ``` 【注意】:与运算,二进制的最小位都为1则返回后边的结果,否则为0 >结果 ![](https://img.tnblog.net/arcimg/hb/358b21f880854cfc865d573e5bf12fe6.png)