Types of GoLang
-
bool
-
Numeric Types
- int8, int16, int32, int64, int
- uint8, uint16, uint32, uint64, uint
- float32, float64
- complex64, complex128
- byte
- rune
-
String
Bool
bool type represents a boolean, either true or false
package main import "fmt" func main(){ a := true b := false fmt.Println("boolean a:",a ,"b:",b) c := a && b d := a || b fmt.Println(c, d) }
a is assigned true, b is assigned false, c is assigned a && b, d is assigned a || b
&&
是逻辑运算符 and,||
是逻辑运算符 or, !是逻辑运算符 not; 所以运行above program 会得到如下结果;
Signed integers
int8 | int16 | int32 | int64 | int | |
---|---|---|---|---|---|
size | 8 bits | 16 bits | 32 bits | 64 bits | 32 || 64 bits |
range | -128 to 127 | -32768 to 32767 | -2^32/2 to 2^32/2-1 | -2^64/2 to 2^64/2 - 1 | int32 || int64 |
int
通常情况是都使用int表示整数, 除非需要表示特定大小的整数; int 的大小和范围取决于底层操作系统;
验证int类型
package main
import (
"fmt"
"unsafe"
)
func main() {
variable_a := 18
var variable_b int = 183
fmt.Printf("type: %T\t%T", variable_a, variable_b) //打印两个变量的类型
fmt.Printf("\nSize: %d\t%d", unsafe.Sizeof(variable_a), unsafe.Sizeof(variable_b))
} //输出两个变量的大小
得到输出如下, 我使用的是64 bits Linux-Manjaro Desktop, 所以验证变量大小是输出为8; 如果是32为的电脑unsafe.Sizeof()
输出结果为 4.
No signed integers
| | uint8 | uint16 | uint32 | uint64 | uint |
|-😐:-😐:-😐:-😐:-😐:-😐
| Size | 8 bits | 16 bits | 32 bits | 64 bits | 32 or 64 |
| Range | 0 - 255 | 0 - 65535 | 0 - 4294967295 | 0 - 1844073709551615 | uint 32 or uint 64 |
Floating point types
float 32
32 bit floating point numbers
float 63
64 bit floating point numbers
Complex types
complex64
具有float32实部和float32虚部的复数数字
complex128
具有float64实部和float64虚部的复数数字
byte
byte就是uint8 的别名
rune
rune 是 int32的别名
强制类型转换
go 对显示输入非常严格. 没有自动\隐性类型转换
package main
import (
"fmt"
"math"
)
func main() {
a := 3
b := 4
var c int
c = int(math.Sqrt(float64(a*a + b*b)))
fmt.Println(c)
}
因为math.Sqrt()需要传入float64, 返回的也是float64 所以这里必须手动强制进行转换 否则编译错误;