```
~~~
package main
import (
"encoding/json"
"fmt"
"time"
)
type Sender = chan <- int //只写通道类型
type Receiver = <- chan int //只读通道类型
func testChan4(mychan chan int) {
n := cap(mychan)
x, y := 1, 1
for i := 0; i < n; i++ {
mychan <- x
x, y = y, x+y
}
close(mychan)
}
func main() {
// 信道遍历
testchan4 := make(chan int, 10)
go testChan4(testchan4)
for x := range testchan4 {
fmt.Println("testchan4 信道值:", x)
}
// 单向信道
var testchan3 = make(chan int)
go func() {
var sender Sender = testchan3
fmt.Println("准备发送数据: 100")
sender <- 100
}()
go func() {
var receiver Receiver = testchan3
num := <- receiver
fmt.Println("接收到的数据是", num)
}()
time.Sleep(time.Second)
// 双向信道
testchan2 := make(chan int)
go func() {
fmt.Println("准备发送数据:100")
testchan2 <- 100
}()
go func() {
num := <- testchan2
fmt.Println("接收到的数据", num)
}()
time.Sleep(time.Second)
// 信道
testchan := make(chan int, 10) //第二个参数大于0时,为缓冲信道,发送端和接收端可以处于异步状态; 为0则为无缓冲信道, 发送端和接收端为同步
fmt.Println("testchan 信道可缓冲数据量", cap(testchan))
testchan<- 1
fmt.Println("testchan 信道当前数据量", len(testchan))
x, ok := <-testchan //从信道中读取数据, x为数据; ok为信道是否关闭, 弱没有关闭, ok为true
fmt.Println("testchan 信道数据:", x)
if ok {
close(testchan)
}
// 协程
go mygo("协程1号")
go mygo("协程2号")
time.Sleep(time.Second)
// 空接口
var i interface{}
// 使用 1
i = 1
fmt.Println(i)
i = "hello"
fmt.Println(i)
i = false
fmt.Println(i)
// 使用 2
myInterface(1)
myInterface("hello")
myInterface(false)
// 使用 3
myInterfaceList(1, "hello", false)
// 类型断言
var i1 interface{} = 10
t1 := i1.(int)
fmt.Println(t1)
t2, ok := i1.(string)
fmt.Println(t2, ok)
// Tag
p1 := People{
Name: "张三",
Age: "18",
}
people1, err := json.Marshal(p1)
if err != nil {
fmt.Println(err.Error())
}
fmt.Printf("%s\n", people1)
p2 := People{
Name: "李四",
Age: "18",
Sex: "男",
}
people2, err := json.Marshal(p2)
if err != nil {
fmt.Println(err.Error())
}
fmt.Printf("%s\n", people2)
// interface, 多态
apple := Apple{
name: "苹果",
quantity: 2,
price: 10,
}
pear := Pear{
name: "梨",
quantity: 3,
price: 9,
}
goods := []Good{apple, pear}
price := formatOrderInfo(goods)
fmt.Println("订单总金额:", price)
// 继承
company := company{
companyName: "腾讯",
companyAddress: "深圳",
}
staff := staff{
name: "张三",
age: 29,
sex: "男",
company: company,
}
fmt.Println(staff.name, "在", staff.companyName, "工作")
fmt.Println(staff.name, "在", staff.company.companyName, "工作")
//结构体
persion := Person{
name: "张三",
age: 18,
sex: "男",
}
persion.FmtPerson()
persion.nextAge()
persion.FmtPerson()
// 变量命名方法
//第一种: 一行生命一个变量
// var <name> <type>
var name1 string = "hello world"
fmt.Println(name1)
//第二种: 声明多个变量
var (
name2 string = "张三"
age int32 = 28
gender string = "男"
)
fmt.Println(name2, age, gender)
//第三种: 声明和初始化一个变量
name3 := "李四"
fmt.Println(name3)
//第四种: 声明和初始化多个变量
name4, age4 := "王五", 30
fmt.Println(name4, age4)
//第五种: new函数声明一个指针变量
var age5 int32 = 31
var age6 = &age5 //&后面变量名, 表示取出该变量的内存地址
fmt.Println("age5", age5, "age6", age6)
// goto
/*
goto flag
fmt.Println("A")
flag:
fmt.Println("B")
*/
}
~~~
```