Golang基础数据类型
整型
- 一般整型
int8 int16 int32 int64
uint8 uint16 uint32 uint64
分别对应8、16、32、64bit的数 - 特别的整型
Unicode字符rune类型是和int32等价的类型,通常用于表示一个Unicode码点。因此rune和int32可以互换使用。
byte类型等价于uint8类型,byte用于强调数据的原始性。
uintptr用来存放指针,多用于底层编程。
int和int32大小相同,但是,是两个不同的类型。
取模的结果总是与被取模数的符号相同
fmt.Println(5%3) //2
fmt.Println(5%-3) //2
fmt.Println(-5%3) //-2
fmt.Println(-5%-3) //-2
符点数
float32、float64
通常应该优先使用float64类型,因为float32类型的累计计算误差很容易扩散。
复数
complex64、complex128
var x complex128 = complex(1, 2) // 1+2i
var y complex128 = complex(3, 4) // 3+4i
fmt.Println(x*y) // "(-5+10i)"
fmt.Println(real(x*y)) // "-5" //取实部
fmt.Println(imag(x*y)) // "10" //取虚部
布尔型
true/false
// btoi returns 1 if b is true and 0 if false.
func btoi(b bool) int {
if b {
return 1
}
return 0
}
字符串
- 一个字符串是一个不可改变的字节序列。
字符串可以包含任意的数据,包括byte值0,通常包含人类可读文本。
s := "hello,world"
l := len(s)
fmt.Print(s[i]) // 0 <= i < len(s)
s[0] = 'L' // compile error: cannot assign to s[0],
// s is ReadOnly
ss := "hello"
if ss > s {
}
if ss == s {
}
- 字符串中包含特殊字符
\a 响铃
\b 退格
\f 换页
\n 换行
\r 回车
\t 制表符
\v 垂直制表符
\' 单引号 (只用在 '\'' 形式的rune符号面值中)
\" 双引号 (只用在 "..." 形式的字符串面值中)
\\ 反斜杠
- 字符串与Byte切片
标准库中有四个包对字符串处理尤为重要:bytes、strings、strconv和unicode包。
strings: 查询、替换、比较、截断、拆分和合并等
bytes: []byte 与字符串有相同结构,相当于字符串的可读形式
strconv: 布尔型、整型数、浮点数和对应字符串的相互转换 unicode: unicode 标准处理字符串
s := "abc"
b := []byte(s)
s2 := string(b)
- 字符串和数字转换 fmt.Sprintf / strconv.Itoa/strconv.Atoi
x := 123
y := fmt.Sprintf("%d", x)
fmt.Println(y, strconv.Itoa(x)) // "123 123"
x, err := strconv.Atoi("123") // x is an int
y, err := strconv.ParseInt("123", 10, 64) // base 10, up to 64 bits
常量
常量表达式的值在编译期计算,而不是在运行期。
常量的值不可修改。
const y float = 0.58 //指定类型
const pi = 3.14 //自动推导
//声明一组常量
const (
e = 2.71
pi = 3.14
)
const (
a = 1
b
c = 2
d
)
fmt.Println(a, b, c, d) // "1 1 2 2"
//iota 常量生成器
type Weekday int
const (
Sunday Weekday = iota //0
Monday //1
Tuesday //2
Wednesday //3
Thursday //4
Friday //5
Saturday //6
)
//每个常量都是1024的幂
const (
_ = 1 << (10 * iota)
KiB // 1024
MiB // 1048576
GiB // 1073741824
TiB // 1099511627776 (exceeds 1 << 32)
PiB // 1125899906842624
EiB // 1152921504606846976
ZiB // 1180591620717411303424 (exceeds 1 << 64)
YiB // 1208925819614629174706176
)