深入理解Golang之interface

1. interface:简单的说,interface是一组method的组合,我们通过interface来定义对象的一组行为。

参考下面这个例子:

package main
 
import "fmt"
 
type Human interface {
    speak(language string)
}
 
type Chinese struct {
}
 
type American struct {
}
 
func (ch Chinese) speak(language string ) {
  fmt.Printf("speck %s\n",language)
}
 
func (am American ) speak(language string ) {
  fmt.Printf("speck %s\n",language)
}
 
func main() {
    var ch Human
    var am Human
 
    ch = Chinese{}
    am = American{}
 
    ch.speak("Chinese")
    am.speak("English")
}

       2. 空interface

3.interface变量存储的类型

package main
import (
  "fmt"
  "strconv"
)

type Element interface{}
type List [] Element

type Person struct {
     name string
     age int
}
//打印
func (p Person) String() string {
   return "(name: " + p.name + " - age: "+strconv.Itoa(p.age)+ " years)"
}
func main() {

  list := make(List, 3)
  list[0] = 1 //an int
  list[1] = "Hello" //a string
  list[2] = Person{"Dennis", 70}

  for index, element := range list{
  switch value := element.(type) {
  case int:
    fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
  case string:
    fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
  case Person:
    fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
  default:
    fmt.Println("list[%d] is of a different type", index)
  }
}

       需要注意:element.(type)语法不能在switch外的任何逻辑里面使用,如果你要在switch外面判断一个类型就使用comma-ok

4. 嵌入interface

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值