go語言之interface

參考文章https://studygolang.com/articles/2652

  • 接口 interface
    interface 類型可以定義一組方法,但是這些不需要實現,並且interface不能包含任何的變量 提供了規範 類似於c++裏面的虛函數。

  • 定義方法

//接口
     type example interface{
     //方法
    		method1(參數列表) 返回值列表
    		method2(參數列表)返回值列表
    
    }

An interface type specifies a method set called its interface.
A variable of interface type can store a value of any type with a method set that is any superset of the interface.
Such a type is said to implement the interface. The value of an uninitialized variable of interface type is nil.

Go 語言提供了另外一種數據類型即接口(interface),它把所有的具有共性的方法定義在一起,這些方法只有函數簽名,沒有具體的實現代碼(類似於Java中的抽象函數),任何其他類型只要實現了接口中定義好的這些方法,那麼就說 這個類型實現(implement)了這個接口

示例:sort接口當中有三個方法 Swap Less Len StudentArray這個類型實現了這三個方法,就相當於實現了sort接口

package main

import(
	"fmt"
	"math/rand"
	"sort"
)

type Student struct{
	Name string
	Id string
	Age int
}
type StudentArray []Student 

func (p StudentArray) Len() int{ 
	return len(p)
} 

func (p StudentArray) Less(i, j int) bool{
	return p[i].Name >p[j].Name
}


func (p StudentArray) Swap(i, j int) {
	p[i] ,p[j] = p[j],p[i]
}


func main(){
	var stus StudentArray
	for i:=0; i<10; i++{
		stu := Student{
			Name:fmt.Sprintf("stu%d",rand.Intn(100)),
			Id:fmt.Sprintf("%d",rand.Int()),
			Age: rand.Intn(100),
		}
		stus = append(stus,stu)
	}

	

	for _,v := range stus{
		fmt.Println(v)
	}

	sort.Sort(stus)
	fmt.Println()
	fmt.Println()
	for _,v := range stus{
		fmt.Println(v)
	}
}

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