Golang值得注意的点

记录了一下最近学习golang语言遗忘的和模糊的知识点,主要涵盖主函数退出返回值、如何编写测试程序、如何定义常量、golang的类型转换、golang中的预定义值、指针与其他语言的差异(主要是C语言),以及运算符等等!

mark

退出返回值

Go中main函数不支持任何返回值,通过os.Exit来返回状态

package main

import (
"fmt"
"os"
)

func main() {
fmt.Println("Hello world")
os.Exit(0)
}

编写测试程序

1、源文件以 _test 结尾:xxx_test.go

2、测试方法名以Test开头:func TestXXX(t *testing.T) {…}

比如我的一个first_test.go文件是这样的:

package try_test

import "testing"

func TestFirstTry(t *testing.T){
t.Log("My First Try")
}

mark

常量定义

package use

import "testing"

func TestConstUser(t *testing.T) {
const(
Monday = iota + 1
Tuesday
Wednesday
)
t.Logf("%d %d %d", Monday, Tuesday, Wednesday)
}


func TestConstant(t *testing.T) {
a := 1
//用位定义的常量标识
const (
Open = 1 << iota
Close
Pending
)

t.Log(a&Open == Open, a&Close == Close, a&Pending == Pending)
}

关于类型转换

1、Go语言不允许隐式类型转换

2、别名和原有类型也不能进行隐式类型转换,比如byte类型和uint8之间就不行

package userType

import "testing"

type MyInt int64

func TestUserType(t *testing.T) {
var a int = 10
var b int64 = 20

//a = b error
//b = a error

var c MyInt = 30

//c = b error
c = MyInt(b) //OK
t.Log(a, b, c)
}

预定义值

func TestIncludeNum(t *testing.T)  {
t.Log(math.MaxInt64)
t.Log(math.MaxFloat64)
t.Log(math.MaxUint32)
t.Log(math.MaxInt8)
}

指针类型

1、不支持指针运算

2、string是值类型,其默认初始化为空串,不是nil

package point

import (
"testing"
)

func TestPoint_01(t *testing.T) {
a := 10
aPtr := &a
//aPtr++ error
t.Log("a =",*aPtr)
}

func TestString_01(t *testing.T) {
var str string
t.Logf("*%s*", str) //**
t.Log(len(str)) //0
}

运算符

golang没有前置的++、前置的–

用==比较数组,相同维数且含有相同个数元素的数组才可以比较,每个元素都相同的才相等

package array_test

import "testing"

func TestArray(t *testing.T) {
a := [...]int{1,2,3,4,5}
b := [...]int{1,2,3,4,5}

t.Log(a)
t.Log(a == b)
}

位运算符中有一个非常神奇的运算符 &^ 按位置零

1 &^ 0 – 1

1 &^ 1 – 0

0 &^ 1 – 0

0 &^ 0 – 0

func TestBitOpt(t *testing.T)  {
a := 7 //0111
//用位定义的常量标识
const (
Open = 1 << iota
Close
Pending
)
//清除Open状态
a = a &^ Open
t.Log(a&Open == Open, a&Close == Close, a&Pending == Pending) //false true true

//清除Close状态
a = a &^ Close
t.Log(a&Open == Open, a&Close == Close, a&Pending == Pending) //false false true
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值