Go系列第一篇-- 基本数据类型
基本类型
bool 布尔类型
string 字符串类型
int int8 int16 int32 int64 有符号整数类型 ,后面的数字表示多少位
uint uint8 uint16 uint32 uint64 uintptr 无符号整数类型 ,后面的数字表示多少位
byte // alias for uint8 字节类型是无符号8位整形的别名
rune // alias for int32,represents a Unicode code point
float32 float64 浮点型 ,分别是32位和64位,对应java中的float和double
complex64 complex128
注意点
与其他主要编程语言的差异
- Go语言不允许隐式类型转换
- 别名和原有类型也不能进行隐式类型转换
什么是隐式类型转换?
java语言
//低类型向高类型转换
short s = 10;
int i = s; // 隐式类型转换
System.out.println(i);
long l = i; // 从int -> long 隐式类型转换
System.out.println(l);
//高 -> 低 不允许
long h = 10000L;
int ll = (int) h; // 强制转换
System.out.println(ll);
go语言中隐式类型转换会报错
package type_test
import (
"testing"
)
type MyInt int64 //指定别名
func TestImplicit(t *testing.T){
var (
a int = 1
b int64 = 2
)
var c MyInt
//错误 cannot use a (type int) as type int64 in assignment
b = a // int -> int64,会报错, Go语言不允许隐式类型转换 ,改为 b = int64(a)
//错误 cannot use b (type int64) as type MyInt in assignment
c = b // 别名和原有类型也不能进行隐式类型转换,改为c=MyInt(b)
t.Log( a , b , c)
}
类型的预定义值
- math.MaxInt64
- math.MaxFloat64
- math.MaxUint32
指针类型
与其他主要编程语言的差异
- 不支持指针运算
- string 是值类型,其默认的初始化值为空字符串,而不是nil
go例子
go指针使用
import (
"testing"
)
func TestPoint(t *testing.T){
a := 1
aPtr := &a
t.Log(a , aPtr)
t.Log("%T %T",a , aPtr)
}
go指针运算(注意:不被允许)伪代码
import (
"testing"
)
func TestPoint(t *testing.T){
a := 1
//报错 invalid operation: &a + 1 (mismatched types *int and int)
aPtr := &a + 1
t.Log(a , aPtr)
t.Log("%T %T",a , aPtr)
}
字符串
func TestString(t *testing.T){
var s string //声明为字符串类型
t.Log("* "+s + " *")
if s == ""{ //判断是否为空
t.Log("s is null")
}
}
以上内容仅供参考,如有错误,请在评论区留言,我们一起讨论吧