十四 Slice切片
func main() {
s := make([]int, 3, 5)
fmt.Println(s, len(s), cap(s))
s = append(s, 1)
fmt.Println(s, len(s), cap(s))
s = append(s, 1)
fmt.Println(s, len(s), cap(s))
s = append(s, 1)
fmt.Println(s, len(s), cap(s))
s = append(s, 1)
t := make([]int, 3)
t = append(t, 1)
fmt.Println(t, len(t), cap(t))
//[0 0 0] 3 5
//[0 0 0 1] 4 5
//[0 0 0 1 1] 5 5
//[0 0 0 1 1 1] 6 10
//[0 0 0 1] 4 6
}
func main() {
a := []int{1, 2, 3, 4}
b := a[0:2]
fmt.Println(a, b)
b[0] = 100
fmt.Println(a, b)
c := make([]int, 3)
copy(c, a)
fmt.Println(a, b, c)
a[0] = 200
fmt.Println(a, b, c)
//[1 2 3 4] [1 2]
//[100 2 3 4] [100 2]
//[100 2 3 4] [100 2] [100 2 3]
//[200 2 3 4] [200 2] [100 2 3]
}
十五 Map的三种声明方式
func main() {
var m map[string]string
if m == nil {
fmt.Println("m is nil")
}
m = make(map[string]string, 10)
m["1"] = "1"
m["s"] = "2"
fmt.Println(m)
o := make(map[int]string)
o[1] = "1"
o[200] = "2"
fmt.Println(o)
p := map[int]string{
22: "ddd",
666: "kkk",
}
fmt.Println(p)
//m is nil
//map[1:1 s:2]
//map[1:1 200:2]
//map[22:ddd 666:kkk]
}
十六 Map的使用方式
func main() {
m := make(map[string]string, 3)
//Create
m["China"] = "Beijing"
m["Japan"] = "Tokyo"
m["US"] = "NewYork"
//Read
for k, v := range m {
fmt.Println(k, v)
}
//Update
m["US"] = "DC"
//Delete
delete(m, "Japan")
delete(m, "DDD")
fmt.Println("============")
for k, v := range m {
fmt.Println(k, v)
}
}
十七 struct的定义和使用
type myint int
type Book struct {
title string
author string
}
func ChangeAuthor1(b Book) {
b.author = "bbb"
}
func ChangeAuthor2(b *Book) {
b.author = "bbb"
}
func main() {
var i myint
i = 123
fmt.Printf("%T %v\n", i, i)
var book Book
book.title = "Learn go"
book.author = "aaa"
fmt.Printf("%T %v\n", book, book)
ChangeAuthor1(book)
fmt.Printf("%T %v\n", book, book)
ChangeAuthor2(&book)
fmt.Printf("%T %v\n", book, book)
//main.myint 123
//main.Book {Learn go aaa}
//main.Book {Learn go aaa}
//main.Book {Learn go bbb}
}
十八 面向对象类的表示
type Hero struct {
Name string
Age int
Level int
}
func (h *Hero) GetName() string {
return h.Name
}
func (h Hero) SetName1(name string) {
h.Name = name
}
func (h *Hero) SetName2(name string) {
h.Name = name
}
func (h *Hero) ShowName() {
fmt.Println(h.Name)
}
func main() {
myHero := Hero{"aaa", 17, 3}
name := myHero.GetName()
fmt.Println(name)
myHero.SetName1("bbb")
myHero.ShowName()
myHero.SetName2("ccc")
myHero.ShowName()
//aaa
//aaa
//ccc
}
十九 对象的继承
type Human struct {
Name string
Sex string
}
type Superman struct {
Human
Sex int
}
func (h *Human) eat() {
fmt.Println("Human eat")
}
func (s *Superman) eat() {
fmt.Println("Superman eat")
}
func main() {
superman := Superman{Human{"aaa", "female"}, 2}
fmt.Println(superman.Sex)
superman.eat()
//2
//Superman eat
}
二十 面向对象的多态的实现和基本要素
type AnimalIF interface {
Sleep()
GetType()
GetColor() string
}
type Cat struct {
Color string
}
func (c *Cat) Sleep() {
fmt.Println("Cat sleep")
}
func (c *Cat) GetType() {
fmt.Println("Type is cat")
}
func (c *Cat) GetColor() string {
return c.Color
}
type Dog struct {
Color string
}
func (c *Dog) Sleep() {
fmt.Println("Dog sleep")
}
func (c *Dog) GetType() {
fmt.Println("Type is dog")
}
func (c *Dog) GetColor() string {
return c.Color
}
func ShowAnimal(animal AnimalIF) {
animal.Sleep()
animal.GetType()
fmt.Println("Color is", animal.GetColor())
}
func main() {
var cat, dog AnimalIF
cat = &Cat{"red"}
dog = &Dog{"blue"}
cat.Sleep()
dog.Sleep()
ShowAnimal(cat)
ShowAnimal(dog)
//Cat sleep
//Dog sleep
//Cat sleep
//Type is cat
//Color is red
//Dog sleep
//Type is dog
//Color is blue
}
基本要素:
- 父类有接口方法,没有被实现
- 多个子类,实现接口的所有方法
- 父类的类型变量的指针,指向子类的具体数据变量
二十一 Interface空接口万能方法和类的断言机制
type Book struct {
author string
}
func MyFunc(arg interface{}) {
fmt.Printf("%T %v\n", arg, arg)
value, ok := arg.(Book)
if ok {
fmt.Println("It is Book:", value)
} else {
println("It is not Book")
}
}
func main() {
book := Book{"aaa"}
MyFunc("aaa")
MyFunc(100)
MyFunc(3.14)
MyFunc(book)
//string aaa
//It is not Book
//int 100
//It is not Book
//float64 3.14
//It is not Book
//main.Book {aaa}
//It is Book: {aaa}
}
二十二 变量的内置pair结构
一个变量在内存中的构造,两部分(Type,Value),Type分为Static类型(int,string),concrete类型
func main() {
file, err := os.OpenFile("c:/dev/a.txt", os.O_RDWR, 0)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(file)
var r io.Reader = file
p := make([]byte, 1000)
read, err := r.Read(p)
if err != nil {
return
}
fmt.Println(string(p), read)
}
//&{0xc000066a00}
//abcd
//6
}
func main() {
book := &Book{}
var r Reader
var w Writer
r = book
r.ReadBook()
w = r.(Writer)
w.WriteBook()
//Read book
//Write book
}
二十三 反射机制
func reflectVar(arg interface{}) {
fmt.Println(reflect.TypeOf(arg))
fmt.Println(reflect.ValueOf(arg))
}
func main() {
var f float64 = 3.13343
reflectVar(f)
//float64
//3.13343
}
type User struct {
Name string
Age int
}
func (u User) ValueCall() {
fmt.Println("Say Hello")
}
func (u *User) PointCall() {
fmt.Println("Say Hello")
}
func DoField(input interface{}) {
inputType := reflect.TypeOf(input)
inputValue := reflect.ValueOf(input)
fmt.Println(inputType.Name(), inputValue)
for i := 0; i < inputType.NumField(); i++ {
field := inputType.Field(i)
fmt.Println(i, field.Type, field.Name, inputValue.Field(i).Interface())
}
fmt.Println(inputValue.NumMethod())
for i := 0; i < inputValue.NumMethod(); i++ {
fmt.Printf("%v\n", inputValue.Method(i).Type())
}
}
func DoMethod(input interface{}) {
inputValue := reflect.ValueOf(input)
fmt.Println(inputValue.NumMethod())
for i := 0; i < inputValue.NumMethod(); i++ {
fmt.Printf("%v\n", inputValue.Method(i))
}
}
func main() {
user := User{"aaa", 12}
DoField(user)
fmt.Println("================")
DoMethod(&user)
//User {aaa 12}
//0 string Name aaa
//1 int Age 12
//1
//func()
//================
//2
//0x642840
//0x642840
}
二十四 反射解析结构体标签
type resume struct {
Name string `info:"hhh"`
Sex string `info:"ttt"`
}
func findTag(input interface{}) {
inputType := reflect.TypeOf(input).Elem()
for i := 0; i < inputType.NumField(); i++ {
fmt.Println(inputType.Field(i).Tag.Get("info"))
}
}
func main() {
var re resume
findTag(&re)
//hhh
//ttt
}
二十五 结构标签在json中的应用
type Movie struct {
Title string `json:"title"`
Price int `json:"rmb"`
Year int `json:"year"`
Actors []string `json:"actors"`
}
func main() {
movie := Movie{"喜剧之王", 60, 2012, []string{"xingye", "zhangbozhi"}}
str, err := json.Marshal(movie)
if err != nil {
return
}
fmt.Printf("%s\n", str)
var new_movie Movie
err = json.Unmarshal(str, &new_movie)
fmt.Println(err, &new_movie)
}
二十六 Goroutine基本模型和调度设计策略
二十七 创建Goroutine
func newTask() {
i := 0
for {
fmt.Println("new goroutine:", i)
i++
time.Sleep(time.Second)
}
}
func main() {
go newTask()
i := 0
for {
fmt.Println("main goroutine:", i)
i++
time.Sleep(time.Second)
}
//main goroutine: 0
//new goroutine: 0
//new goroutine: 1
//main goroutine: 1
//main goroutine: 2
//new goroutine: 2
}
func main() {
defer fmt.Println("main exit")
go func() {
defer fmt.Println("Goroutine exit")
func() {
defer fmt.Println("func exit")
runtime.Goexit()
fmt.Println("func")
}()
fmt.Println("Goroutine")
}()
for {
time.Sleep(time.Second)
}
//func exit
//Goroutine exit
}
二十八 Channel的定义和使用
func main() {
c := make(chan string)
go func() {
time.Sleep(time.Second)
c <- "555"
}()
str := <-c
fmt.Println(str)
//555
}
二十九 Channel有缓存和无缓存
func main() {
c := make(chan int, 3)
go func() {
for i := 0; i < 4; i++ {
c <- i
fmt.Println("add channel", i, "len:", len(c), "cap:", cap(c))
}
}()
time.Sleep(time.Second)
for i := 0; i < 4; i++ {
m := <-c
fmt.Println("get channel", m)
}
time.Sleep(time.Second)
//add channel 0 len: 1 cap: 3
//add channel 1 len: 2 cap: 3
//add channel 2 len: 3 cap: 3
//get channel 0
//get channel 1
//get channel 2
//get channel 3
//add channel 3 len: 3 cap: 3
}
三十 Channel关闭
func main() {
c := make(chan int)
go func() {
for i := 0; i < 5; i++ {
c <- i
fmt.Println("add channel", i, "len:", len(c), "cap:", cap(c))
}
close(c)
}()
for {
if m, ok := <-c; ok {
fmt.Println("get channel, ok", m)
} else {
fmt.Println("get channel, false", m)
break
}
}
//add channel 0 len: 0 cap: 0
//get channel, ok 0
//get channel, ok 1
//add channel 1 len: 0 cap: 0
//add channel 2 len: 0 cap: 0
//get channel, ok 2
//get channel, ok 3
//add channel 3 len: 0 cap: 0
//add channel 4 len: 0 cap: 0
//get channel, ok 4
//get channel, false 0
}
三十一 Channel关闭
func main() {
c := make(chan int)
go func() {
for i := 0; i < 3; i++ {
c <- i
fmt.Println("add channel", i, "len:", len(c), "cap:", cap(c))
}
close(c)
}()
for d := range c {
fmt.Println("get channel, ok", d)
}
fmt.Println("end")
//get channel, ok 0
//add channel 0 len: 0 cap: 0
//add channel 1 len: 0 cap: 0
//get channel, ok 1
//get channel, ok 2
//add channel 2 len: 0 cap: 0
//end
}
三十二 Channel和Select
func fib(c, q chan int) {
x, y := 1, 1
for {
select {
case c <- y:
x, y = x+y, x
case <-q:
return
}
}
}
func main() {
c := make(chan int)
q := make(chan int)
go func() {
for i := 0; i < 6; i++ {
fmt.Println(<-c)
}
q <- 0
}()
fib(c, q)
//1
//1
//2
//3
//5
//8
}