GO语言学习(四):接口与channel并发

一.接口
1.接口

type Humaner interface {
   //方法,只有声明,没有实现,有别的类型实现
   sayhi()
}

type Student struct {
   name string
   id int
}
//Student实现了此方法
func (tmp *Student) sayhi(){
   fmt.Printf("Student[%s, %d] sayhi\n", tmp.name, tmp.id)
}

type Teacher struct {
   addr string
   group string
}

//Teacher实现了此方法
func (tmp *Teacher) sayhi() {
   fmt.Printf("Teacher[%s, %s] sayhi\n", tmp.addr, tmp.group)
}

//Mystr实现了此方法
type MyStr string
func (tmp MyStr) sayhi() {
   fmt.Printf("MyStr[%s] sayhi\n", tmp)
}

func WhoSayHi(i Humaner){
   i.sayhi()
}
//定义一个普通函数,函数的参数为接口类型
//只有一个函数,可以有不同表现形态,多态
func main(){
   s := &Student{"mike", 666}
}

func main01(){
    //定义接口类型变量
    //var i Humaner
    is := []Humaner{&Student{"mike", 666}, &Teacher{"bj", "go"}, MyStr("hello mike")}
    for _, human := range is{
       human.sayhi()
    }
    //只要实现了此接口方法的类型,那么这个类型的变量(接受者的类型)就可以给i赋值
    //s := &Student{"mike", 666}
    //i = s
    //i.sayhi()
    //
    //t := &Teacher{"bj", "go"}
    //i = t
    //i.sayhi()
    //
    //var str MyStr = "hello mike"
    //i = &str
    //i.sayhi()

}

2.接口继承

type Humaner interface {
   //方法,只有声明,没有实现,有别的类型实现
   sayhi()
}

type Personer interface {
   Humaner //匿名函数,继承了sayhi()
   sing(lrc string)
}
type Student struct{
   name string
   id int
}
func (tmp *Student) sayhi() {
   fmt.Printf("%s : %d\n", tmp.name, tmp.id)
}
func (tmp *Student) sing(lrc string) {
   fmt.Println("Student is singing", lrc)
}
func main(){
   var i Personer
   s := &Student{"mike", 666}
   i = s
   i.sayhi()
   i.sing("学生2222")
}

3.空接口
//空接口不包含任何的方法,正因为如此,所有的类型都实现了空接口
//因此空接口可以存储任意类型的数值

4.error函数
二.并行与并发
1.定义:
并行:多个进程使用多个cpu
并发:多个进程采用时间片轮转的方法使用单个cpu
2.goroutine

  • 创建
func newtask(){
   for {
      fmt.Println("this is anewTask")
      time.Sleep(time.Second)  //延时1s
   }
}
func main(){
   go newtask() //新建一个协程,新建一个任务

   for {
      fmt.Println("this is a main goroutine")
      time.Sleep(time.Second)  //延时1s
   }
}
  • 主协程退出了,其他子协程也要跟着退出
func main(){
   go func() {
      i := 0
      for {
         i++
         fmt.Println("子协程 i = ", i)
         time.Sleep(time.Second)

      }
   }()
   i := 0
   for {
     i++
     fmt.Println("main i = ", i)
     time.Sleep(time.Second)

     if i==2{
        break
     }
   }

}
  • runtime.Gosched()让出时间片,先让别的协议执行,它执行完,再回来执行此协程
func main(){
  go func() {
     for  i := 0; i < 5; i++ {
        fmt.Println("go")
     }
  }()

  for i := 0; i < 2; i++{
     //让出时间片,先让别的协议执行,它执行完,再回来执行此协程
     runtime.Gosched()
     fmt.Println("hello")
  }

}

猜你喜欢

转载自blog.csdn.net/weixin_43011810/article/details/85060105