05丨变量、常量以及与其他语言的差异

05丨变量、常量以及与其他语言的差异

编写测试程序

1. 源码文件以 _test 结尾:xxx_test.go
2. 测试方法名以 Test 开头:func TestXXX(t *testing.T) {…}

变量赋值

与其他主要编程语言的差异

  • 赋值可以进行自动类型推断
  • 在一个赋值语句中可以对多个变量进行同时赋值
  • 支持变量交换

实现 Fibonacci数列

1,1,2,3,5,8,13

package fib

import (
    "testing"
)

func TestFibList(t *testing.T) {
    //变量赋值:
    //第一种方法
    // var a int = 1
    // var b int = 1

    //第二种 多个赋值
    // var (   //     a int = 1
    //     b     = 1
    // )

    //第三种 类型推断
    a := 1
    // a := 1
    b := 1
    t.Log(a)
    for i := 0; i < 5; i++ {
        t.Log(" ", b)
        //tmp := a
        //a = b
        //b = tmp + a

        a,b=b,a+b    // 交换变量

    }

}

func TestExchange(t *testing.T) {
    a := 1
    b := 2
    //正常的交换变量方法
    // tmp := a
    // a = b
    // b = tmp

    //简洁的交换
    a, b = b, a
    t.Log(a, b)
}

常量定义

与其他主要编程语言的差异

  • 快速设置连续值
const (
 Monday = iota + 1
 Tuesday
 Wednesday
 Thursday
 Friday
 Saturday
 Sunday
)

 

const (
 Open = 1 << iota
 Close
 Pending
)

 

 
测试代码
 
package constant_test

import "testing"

const (
    Monday = 1 + iota //连续的常量简洁的写法
    Tuesday
    Wednesday
)

func TestConstantTry(t *testing.T) {
    t.Log(Monday, Tuesday, Wednesday) //constant_try_test.go:18: 1 2 3
}

const (
    Readable = 1 << iota     // 位运算
    Writable
    Executable
)

func TestConstantTry1(t *testing.T) {

    //a := 7 // 0111 //    constant_try_test.go:28: true true true
    a := 1 //0001 //    constant_try_test.go:26: true false false
    t.Log(a&Readable == Readable, a&Writable == Writable, a&Executable == Executable)
}

 

posted @ 2021-01-20 01:42  元贞  阅读(54)  评论(0)    收藏  举报