Go(6 [接口 類型斷言])

Go接口 Interface

定義:Interface類型可以定義⼀組⽅法,⽤來表示⼀個對象的⾏爲特徵。 interface不能包含任何變量。

代碼:

  1. interface關鍵字

  2. 定義接口類型,接口是引用類型

  3. 是抽象的,具體的類纔可以調用

type Aniaml interface {
    //定義2個是行爲特徵,方法
    Eat()
    Talk()
}

定義2個struct

//只要一個具體的struct實現這個接口的類型的所有方法,也就是具有這個接口的所有行爲特徵,都是可以存儲到這個接口類型變量裏面

type Dog struct{
    Name string
}
type Cat struct{
    Name string
}
//添加2個方法
func (d *Dog) Eat()  {
    fmt.Println(d.Name,"is eat")
}
func (d1 *Dog) Talk()  {
    fmt.Println(d1.Name,"is 旺旺")
}
func main(){

    //那a animal類型的接口類型的變量,它裏面就可以存儲任何這個 函數包含着2個類型
     var a Aniaml
    //dog具體的實例
     var d Dog
     d.Eat()
     
     a = &d
     a.Eat()

}

接口實現

go中的接口,不需要顯示的實現,只要一個對象,實現了接口類型的所有方法,那麼這個對象就實現了這個接口

記住是實現所有方法!!!!

如果應該對象實現了多個interface類型的方法,那麼這個對象就實現了多個接口

測試:type Aniaml interface {

    Eat()

    Talk()

}func TestOperator()  {

    //定義一個接口類型的切片:  

    var animallist []Aniaml

    //實例化

    d := &Dog{

        Name:"旺財",

    }

    animallist = append(animallist,d)

    d1 := &Dog{

        Name:"狗子",

    }

    animallist = append(animallist,d1)

    c := &Cat{

        Name:"喵喵1",

    }

    animallist = append(animallist,c)

    c1 := &Cat{

        Name:"喵喵2",

    }

    animallist = append(animallist,c1)


    for _,v:=range animallist{


        v.Eat()

        v.Talk()


    }

}

空接口,Interface{}

定義:空接口沒有任何方法,所以所以類型都實現了空接口

package main

import "fmt"

func main()  {

    //空接口, 既可以存字符串又可以存int

    var a interface{}

    var b int = 100

    a = b

    fmt.Println(a)


    var c string =" hello "

    a = c

    fmt.Println(a)


}

類型斷言:

定義:如果我們反向要知道這個接口變量⾥⾯實際存儲的是哪個類型的對象可以採⽤以下⽅法進⾏轉換

    var t int

    var x interface{}

    x = t

    y, ok = x.(int) //轉成int,帶檢查

列子二:

////a.(type)  獲取變量的類型    


    switch t := a.(type) {

    case *Dog:

        t.Eat()

        fmt.Printf("t is dog\n")

    case *Cat:

        t.Eat()

        fmt.Printf("t is cat\n")

    }

栗子三: 

package main



import (
	"fmt"
)

func justify(items ...interface{}) {
	for index, v := range items {
		switch v.(type) {
		case int:
			fmt.Printf("第 %d 個參數 is int\n", index)
		case int32:
			fmt.Printf("第 %d 個參數 is int32\n", index)
		case float32:
			fmt.Printf("第 %d 個參數 is float32\n", index)
		
		}
	}
}

func main(){
	var a int
	var b float32
	var c int32
	justify(a, b, c)

	
}

判斷一個變量是否實現了指定接口:

栗子:

//WeChatPay 是一個struct類型,

//pay是一個接口


    type Pay interface {

        pay(user_id int64,money float64) error

    }

    

    type WeChatPay struct {

    

    }

    

    func (w *WeChatPay) pay(user_id int64,money float64) error  {

        fmt.Println("微信支付!!")

        return nil

    }

//應該先把weChat實例存到一個空的接口,然後使用空的interface 是否實現了這個接口

    weChat := &WeChatPay{}

    var tmp interface{} = weChat

    _, ok := tmp.(Pay)

    

    if ok {

        fmt.Println("weChat is implement Pay interface")

        //phone.OpenPay("wechat_pay", weChat)

    }

栗子:

  1. 使用接口的方法實現sort功能

###查看系統sort內部的接口 是這3個接口.

type Interface interface {

    // Len is the number of elements in the collection.

    Len() int

    // Less reports whether the element with

    // index i should sort before the element with index j.

    Less(i, j int) bool

    // Swap swaps the elements with indexes i and j.

    Swap(i, j int)

}

所以咱只要實現了這3個接口,就可以能用sort了

package main


import (

    //"sort"

    "math/rand"

    "fmt"

    "sort"

)

type Student struct {

    name string

    age int

    source float32

}


type StudentSlice []*Student


func (p StudentSlice) Len() int {


    return len(p)

}


func (p StudentSlice) Less(i,j int) bool {

    //fmt.Printf("i,j\n",i,j)

    return p[i].age < p[j].age

}


func (p StudentSlice) Swap(i,j int)   {

    p[i],p[j] = p[j],p[i]

}


func main()  {

    var studentarr StudentSlice


    for i:=0;i<10;i++{

        var s = &Student{

            name :fmt.Sprintf("任%d",i),

            age: rand.Intn(100),

            source:rand.Float32() * 100,

        }

        studentarr = append(studentarr, s)

    }

    //系統的sort

     //sort.Sort(studentarr)

    //自定義的sort

    site_sort(studentarr)

    for i:=0;i<len(studentarr);i++{

        fmt.Printf("%#v\n",studentarr[i])

    }



}

栗子2:

package main


type SortInterface interface {

    Len() int

    Less(i,j int) bool

    Swap(i,j int)

}


func site_sort(a SortInterface)  {

    for i :=a.Len() -1 ;i>0;i--{

        for j:=0;i<i;j++{

            if a.Less(j+1,j){

                a.Swap(j,j+1)

            }

        }

    }

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章