8.基本数据类型
Go的基本数据类型有数字,字符串,布尔型。
a.布尔类型
var b bool//var b bool = true/var b = false
操作符==和!=,取反!b,&&和||操作符,格式化%t
例:
1: func main() {2: var a bool3: fmt.Println(a)4: a = true5: fmt.Println(a)6: a = !a7: fmt.Println(a)8: var b bool = true9: if a == true && b == true {
10: fmt.Println("right")
11: }else{
12: fmt.Println("not right")
13: }14: if a == true || b == true {
15: fmt.Println("||right")
16: }else{
17: fmt.Println("not right")
18: }19: fmt.Printf("%t-%t ", a, b)
20: }
b.整数和浮点数类型
有符号整数int和无符号整数uint:
int8,int16,int32,int64和uint8,uint16,uint32,uint64
与操作系统相关:
int和uint
浮点数:
float32和float64
注意:所有的整数初始化为0,所有浮点数初始化为0.0.布尔类型初始化为false,例:
1: func main(){2: var a int83: a = 184: fmt.Println("a=", a)
5: a = -126: fmt.Println("a=", a)
7: var b int8: b = 2321123329: fmt.Println("b=", b)
10: var c float32 = 1.1324211: fmt.Println("c=", c)
12: }
Go是强类型语言,不同类型相加以及赋值一般是不允许的,下面是实现不同类型相加:
1: b = int(a)
格式化输出:
1: fmt.Printf("a=%d a=%x c=%f
", a, a, c)
输出结果:
1: //a=-12 a=-c c=1.132420
c.字符串类型
var str string
var str string = "hello world!"
字符串输出占位符%s
万能输出占位符%v
两种表示方式:
双引号""和反引号``(字符原样输出)
1: func main() {2: var a string = "hello world!"3: var b = "hello world_2!"
4: fmt.Printf("a=%s b=%s ", a, b)
5: c := a6: fmt.Printf("c=%s ",c)
7: d := "d:hello world_3!"
8: fmt.Println(d)9: fmt.Printf("a=%v b=%v c=%v d=%v ", a, b, c, d)
10: e := `c:11: hello hello hello12: hello hello `13: fmt.Println("e=",e)
14: }
字符串常用操作:
长度:len(str)
拼接:+,fmt.Sprintf
分割:strings.Split
包含:strings.Contains
前缀或后缀判断:strings.HasPrefix,strings.HasSuffix
子串出现的位置: strings.Index(),strings.LastIndex()
join操作: strings.Join(a[]string, sep string)
例:
1: func main(){2: c := "hello world!"
3: clen := len(c)4: fmt.Printf("len of c = %d ", clen)
5: c1 := c + c6: c2 := fmt.Sprintf("%s%s", c, c)
7: fmt.Printf("c1=%s c2=%s ", c1, c2)
8: ips := "10.108.34.30;10.108.34.34"
9: ipsArray := strings.Split(ips, ";")
10: fmt.Println("ips[0]=",ipsArray[0])
11: result := strings.Contains(ips, "10.108.34.31")
12: fmt.Println(result)13: baidu_index := "http://baidu.com"
14: if strings.HasPrefix(baidu_index, "http"){15: fmt.Printf("str is http url")
16: }else{
17: fmt.Printf("str is not http url")
18: }19: index := strings.Index(baidu_index, "baidu")20: fmt.Printf("baidu is index:%d ", index)21: index = strings.LastIndex(baidu_index, "baidu")22: fmt.Printf("baidu last index:%d ", index)23: var str []string = []string{"10.237.8.2","10.237.8.2","10.237.8.2"}24: result_2 := strings.Join(str, "|")
25: fmt.Printf("result_2=%s ", result_2)
26: }
操作符:(这个太简单就不写例子了)
逻辑操作符: ==,!=,<,<=,>=
算数操作符: +,-,*,/,%
9.go语言的基本结构
1: package main2: import (
3: "fmt"
4: "os"
5: )6: func main() {7: fmt.Println(“hello, world”)8: }
1. 任何一个代码文件隶属于⼀个包
2. import 关键字,引用其他包:
3. 开发可执行程序,package main,并且有且只有一个main入口函数
4. 包中函数调用:
a. 同一个包中函数,直接用函数名调⽤
b. 不同包中函数,通过包名+点+ 函数名进行调用
5. 包访问控制规则:
a. ⼤写意味着这个函数/变量是可导出的
b. ⼩写意味着这个函数/变量是私有的,包外部不不能访问