基本数据类型及转换
代码
// example.go
package test
import "fmt"
func BasicDataTypes() {
fmt.Println("整数类型")
var (
n1 = 0b0101 //二进制,默认为int
n2 int8 = 0o77 //八进制
n3 uint16 = 0xAF //十六进制
)
//%T代表打印该变量的类型
fmt.Printf("n1=%v,type is %T\n", n1, n1)
fmt.Printf("n2=%v,type is %T\n", n2, n2)
fmt.Printf("n3=%v,type is %T\n", n3, n3)
fmt.Println("浮点类型")
var (
f1 = 1.0 //默认为float64
f2 float32 = 1
f3 float64 = 2
)
fmt.Printf("f1=%v,type is %T\n", f1, f1)
fmt.Printf("f2=%v,type is %T\n", f2, f2)
fmt.Printf("f3=%v,type is %T\n", f3, f3)
fmt.Println("类型转换")
n2 = int8(n3) //将n3强制转换成int8类型
fmt.Printf("n2=%v\n", n2)
fmt.Println("字符型")
var (
c1 byte //默认为0,是uint8的别名
c2 = '0'
c3 rune = '中' //rune类型,是int32的别名
)
fmt.Printf("c1的码值=%v,码值对应的字符%c,type is %T\n", c1, c1, c1)
fmt.Printf("c2的码值=%v,码值对应的字符%c,type is %T\n", c2, c2, c2)
fmt.Printf("c3的码值=%v,码值对应的字符%c,type is %T\n", c3, c3, c3)
fmt.Println("布尔型")
var bool1 bool = true
fmt.Printf("bool1=%v,type is %T\n", bool1, bool1)
fmt.Println("字符串")
var s1 string = "hello"
fmt.Println(s1 + " world")
fmt.Println(s1, "world") //跟上一个等价,可以将逗号替换成空格
fmt.Println(len("XIXIXI")) //可以求字符串的长度
}
// main.go
package main
import (
"GoExample/test"
)
func main() {
test.BasicDataTypes()
}
标签:基本,转换,fmt,数据类型,Printf,Println,n2,type,码值
From: https://www.cnblogs.com/gao79135/p/17738995.html