functestRangeFor(){
s :="123阿斯蒂"// go语言中的字符串实际上是类型为byte的只读切片,所以输出都是字节流的的值// 49 50 51 38463 26031 33922for_, c :=range s {
fmt.Print(c," ")}
fmt.Println()// 49 50 51 233 152 191 230 150 175 232 146 130for_, c :=range[]byte(s){
fmt.Print(c," ")}
fmt.Println()// 49 50 51 38463 26031 33922for_, c :=range[]rune(s){
fmt.Print(c," ")}
fmt.Println()// 1 2 3 阿 斯 蒂for_, c :=range s {
fmt.Print(string(c)," ")}
fmt.Println()// 49 50 51 233 152 191 230 150 175 232 146 130for i :=0; i <len(s); i++{
fmt.Print(s[i]," ")}}
5. 多返回值
funcswapInt(a int, b int)(int,int){
a, b = b, a
return a, b
}functestFunction(){
a :=1
b :=2
a, b =swapInt(a, b)
fmt.Println(a," ", b)}
### 6.switch语句
functestSwitch(){for{
x :=0_, ok := fmt.Scanln(&x)if ok !=nil{break}// 默认breakswitch x {case1,2,3:
fmt.Println("A")case5:
fmt.Println("B")case6:
fmt.Println("fallthrough")fallthroughdefault:
fmt.Println("default")}}}
6. 函数类型
type greeting func()stringfunctestFunc(f greeting){
fmt.Println(f())}functestFunc1(){testFunc(func()string{return"Hello"})}
7. Goroutine
funcTimeAdd(i, j int){
time.Sleep(time.Second)
fmt.Println(i + j)}functestAdd(){for i :=0; i <10; i++{goTimeAdd(i, i)}
time.Sleep(time.Second *3)}
type People struct{
Name string`json:"peopleName"`
Age int}functestJson(){
a :=[5]int{1,2,3,4}
s,_:= json.Marshal(a)
fmt.Println(string(s))
m :=make(map[string]string)
m["A"]="1"
m["B"]="2"
m["C"]="3"
s,_= json.Marshal(m)
fmt.Println(string(s))
m1 :=make(map[string]interface{})
m1["Name"]="AAA"
m1["Age"]=15
m1["Die"]=true
s,_= json.MarshalIndent(m1,""," ")
fmt.Println(string(s))
p := People{"Abc",12,}
s,_= json.MarshalIndent(p,""," ")
fmt.Println(string(s))var j interface{}
json.Unmarshal(s,&j)
fmt.Printf("%v\n", j)var p1 People
json.Unmarshal(s,&p1)
fmt.Println(p1)// 读写json文件
file,_:= os.OpenFile("./test.json", os.O_CREATE|os.O_TRUNC|os.O_WRONLY,0666)
encoder := json.NewEncoder(file)
encoder.Encode(p)
file.Close()var p2 People
file,_= os.Open("./test.json")
decoder := json.NewDecoder(file)
decoder.Decode(&p2)
fmt.Println(p2)
file.Close()
os.Remove("./test.json")}
14. Channel
functestChannel(){// ch := make(chan int)
ch :=make(chanint,5)gofunc(ch chanint){for i :=0; i <20; i++{
ch <- i
fmt.Println("Send: ", i)}}(ch)gofunc(ch chanint){for i :=0; i <20; i++{
n :=<-ch
fmt.Println("Receive: ", n)}}(ch)
time.Sleep(time.Second)}
15. Channel
funccreateWoker(name string, ch chanint)func(){returnfunc(){fortrue{
i :=<-ch
time.Sleep(time.Millisecond *10)
fmt.Println(name,": ", i)}}}functestChannel2(){
ch :=make(chanint,100)for i :=0; i <4; i++{gocreateWoker(strconv.Itoa(i), ch)()}for i :=0; i <100; i++{
ch <- i
}
time.Sleep(time.Second *2)}
functestRandom(){
r := rand.New(rand.NewSource(time.Now().UnixNano()))
n := r.Intn(101)for{var input string
fmt.Scan(&input)if input =="exit"{break}
number, err := strconv.Atoi(input)if err !=nil{
fmt.Println(err.Error())break}if number == n {
fmt.Println("Win")break}elseif number > n {
fmt.Println("Big")}else{
fmt.Println("Small")}}}
functestNil(){// nil是不能比较的// 如果两个比较的nil值之一是一个接口值, 而另一个不是, 假设它们是可比较的, 则比较结果总是 false。// 原因是在进行比较之前, 接口值将转换为接口值的类型。转换后的接口值具有具体的动态类型, 但其他接口值没有。这就是为什么比较结果总是错误的。// fmt.Println(nil == nil) // invalid operation: nil == nil (operator == not defined on nil)// 按照Go语言规范,任何类型在未初始化时都对应一个零值:布尔类型是false,整型是0,// 字符串是"",而指针、函数、interface、slice、channel和map的零值都是nil。var p *int
fmt.Println(p)// <nil>
fmt.Println(p ==nil)// truevar s []int
fmt.Println(s)// []
fmt.Println(s ==nil)// true}
23. strings
functestStrings(){
fmt.Println(strings.Contains("Abc","Ab"))// true
fmt.Println(strings.Contains("Abc啊","啊"))// true
fmt.Println(strings.Index("ABC","BC"))// 1
fmt.Println(strings.IndexAny("ABC","CBA"))// 0
fmt.Println(strings.ToUpper("abc"))
fmt.Println(strings.ToLower("ABC"))
fmt.Println(strings.Title("hello world"))// Hello World
fmt.Println(strings.TrimSpace(" \n\ta\t\n "))// a
fmt.Println(strings.Trim("!!a;bc;;","!;"))// a;bc
fmt.Println(strings.Compare("a","b"))// -1
fmt.Println(strings.Compare("b","a"))//1
fmt.Println(strings.Compare("a","a"))//0
fmt.Println(strings.Split("a;b;c",";"))// [a b c]
fmt.Println(strings.Split("a;b;c;",";"))// [a b c ]
fmt.Println(strings.SplitAfter("a;b;c",";"))// [a; b; c]
fmt.Println(strings.SplitAfter("a;b;c;",";"))// [a; b; c; ]
fmt.Println(strings.ReplaceAll("AbAcAd","A","HH"))// HHbHHcHHd
fmt.Println(strings.Join([]string{"A","B","C","D"},";"))// A;B;C;D// %U: Unicode格式:U+1234,等同于 "U+%04X"// %c:相应Unicode码点所表示的字符
fmt.Printf("%c\n",'a')// a
fmt.Printf("%c\n",'啊')// 啊
fmt.Printf("%U\n",'a')// U+0061
fmt.Printf("%U\n",'啊')// U+554A}
24. flag
functestFlag(){
fmt.Println(os.Args)
name := flag.String("name","","Input Name")
age := flag.Int("age",0,"Input Age")
check := flag.Bool("check",false,"Input check")
flag.Parse()
fmt.Println(*name)
fmt.Println(*age)
fmt.Println(*check)}
25. 继承
type Animal struct{
name string}func(animal *Animal)SetName(name string){
animal.name = name
}func(animal Animal)GetName()string{return animal.name
}func(animal Animal)Eat(){
fmt.Println("Eating")}type Fish struct{
Animal // 持有父类,相当于继承父类
fins int}func(fish *Fish)Swim(){
fmt.Println("Swimming")}functestInherit(){
f :=&Fish{Animal{"fish"},4}
f.Eat()
f.Swim()
f.SetName("fish2")
fmt.Println(f.GetName())
fmt.Println(f.name)
fmt.Println(f.fins)}
26. 多态
// 接口Windowtype Window interface{Create(title string)boolPrintTitle()}// 类型Paneltype Panel struct{
title string}func(panel *Panel)Create(title string)bool{
panel.title = title
fmt.Println("Create Panel!")returntrue}func(panel *Panel)PrintTitle(){
fmt.Println("Print panel title:", panel.title)}// 类型Controltype Control struct{
title string}func(control *Control)Create(title string)bool{
control.title = title
fmt.Println("Create Control!")returntrue}func(control Control)PrintTitle(){
fmt.Println("Print control title:", control.title)}// 类型ComboBox// 继承Control类,同时实现了Window接口type ComboBox struct{
Control
}func(cb *ComboBox)Create(title string)bool{
cb.title = title
fmt.Println("Create ComboBox!")returntrue}func(cb ComboBox)PrintTitle(){
fmt.Println("Print ComboBox title:", cb.title)}func(cb ComboBox)GetSelection(){
fmt.Println("Select 1")}functestPolymorphism(){
windows :=[]Window{}
windows =append(windows,new(Panel))
windows =append(windows,new(Control))
windows =append(windows,new(ComboBox))// 多态for_, w :=range windows {
w.Create("123")}for_, w :=range windows {
w.PrintTitle()}// 断言类型的语法:x.(T),这里x表示一个接口的类型,T表示一个类型(也可为接口类型)。// 一个类型断言检查一个接口对象x的动态类型是否和断言的类型T匹配。// Type switchfor_, w :=range windows {switch w.(type){case*Panel:
fmt.Println("I am Panel")case*Control:
fmt.Println("I am Control")case*ComboBox:
fmt.Println("I am ComboBox")}}// Type assertionfor_, w :=range windows {if cb, ok := w.(*ComboBox); ok {
cb.GetSelection()}}// 接口实例可以接收子类指针// 父类实例指针不能接收子类指针// 也就是说定义了接口才能实现多态
cb :=new(ComboBox)// var c *Control// c = cb // cannot use cb (type *ComboBox) as type *Control in assignmentvar w Window
w = cb
w.PrintTitle()}
type InvalidParamError struct{
invalidValue int}func(err InvalidParamError)Error()string{return fmt.Sprintf("Invalid param: %d.", err.invalidValue)}funcvalidateA(a int)error{if a ==0{panic("Can't be zero")}if a ==1|| a ==2|| a ==3|| a ==4{return&InvalidParamError{a}}if a ==7{panic(&InvalidParamError{a})}returnnil}functestPanic(){deferfunc(){
err :=recover()if err !=nil{
fmt.Println(err)
fmt.Println("End1")}}()if err :=validateA(2); err !=nil{
fmt.Println(err)}// validateA(0)validateA(7)
fmt.Println("End2")}
31. 反射
type RParent struct{
Name string
Age int}type RSon struct{
RParent
School string}func(s RSon)CanSwim()bool{returntrue}func(s *RSon)Set(name string, age int, school string){
s.Name = name
s.Age = age
s.School = school
}functestReflect(){var object interface{}
object = RSon{RParent{"AAA",14},"BBCC"}// 1. reflect.TypeOf: 返回类型信息
objType := reflect.TypeOf(object)
fmt.Println(objType)// main.RSon
fmt.Println(objType.Name())// RSon (类型名称)
fmt.Println(objType.Kind())// struct (原始类型)
fmt.Println(objType.NumField())// 2 (属性个数,RParent算一个整体属性)
fmt.Println(objType.NumMethod())// 1 (方法个数)// 遍历属性名称和类型// RParent main.RParent// School stringfor i :=0; i < objType.NumField(); i++{
filed := objType.Field(i)
fmt.Println(filed.Name, filed.Type)}// 遍历方法名称和类型// Swim func(main.RSon)for i :=0; i < objType.NumMethod(); i++{
method := objType.Method(i)
fmt.Println(method.Name, method.Type)}// 获取父类属性,(0,1)代表RSon的第零个属性中的第一个属性
fmt.Println(objType.FieldByIndex([]int{0,1}).Name)// Age// 2. reflect.ValueOf: 返回值信息
objValue := reflect.ValueOf(object)
fmt.Println(objValue)// {{AAA 14} BBCC}// 遍历属性的值// {AAA 14}// BBCCfor i :=0; i < objValue.NumField(); i++{
fmt.Println(objValue.Field(i).Interface())}// 获取父类属性的值
fmt.Println(objValue.FieldByIndex([]int{0,0}).Interface())// AAA// 该类型不能修改值,指针类型才可以// panic: reflect: reflect.flag.mustBeAssignable using unaddressable value// objValue.FieldByName("School").SetString("123")// 3. 修改属性值var objectp interface{}
r :=&RSon{RParent{"AAA",14},"BBCC"}
objectp = r
objpValue := reflect.ValueOf(objectp)
fmt.Println(objpValue.Kind())// ptr// 获取指针指向的对象
elem := objpValue.Elem()// 遍历属性的值// {AAA 14}// BBCCfor i :=0; i < elem.NumField(); i++{
fmt.Println(elem.Field(i).Interface())}// 修改属性
elem.FieldByName("School").SetString("1234")
fmt.Println(r)// &{{AAA 14} 1234}// 调用方法
m1 := objpValue.MethodByName("CanSwim")
r1 := m1.Call([]reflect.Value{})
fmt.Println(r1[0].Interface())// true
m2 := objpValue.MethodByName("Set")
m2.Call([]reflect.Value{reflect.ValueOf("DDD"), reflect.ValueOf(123), reflect.ValueOf("CCC")})
fmt.Println(r)// &{{DDD 123} CCC}}