go語言---接口

package main

import (
	"fmt"
	"sort"
)

// type  people []string
// func (p people)Len() int{ 
// 	return len(p)
// }
// func (p people)Swap(i,j int){
// 	p[i],p[j] = p[j],p[i]
// }
// func (p people)Less(i,j int) bool{
// 	return p[i]>p[j]
// }

// type recover struct{
// 	sort.Interface
// }

// func (r recover)Less(i,j int)bool{
// 	return r.Interface.Less(j,i)
// }

// func  Recover( data sort.Interface) sort.Interface{
// 	return  recover{data}
// }

/* 定義一個類 */

type person struct{
	name string
	age string
}

func (p person) getName()string{
	return p.name
}



type people []string
func (p people)Len()int {
	return len(p)
}

func (p people)Swap(i,j int){
	p[i],p[j] = p[j],p[i]
}
func (p people)Less(i,j int)bool{
	return p[i] > p[j]
}

/**
*定義一個接口,與java的接口定義相似
*接口只是對一個標準的定義
*不須要繼承,只要知足這個接口裏面的方法定義均可以認爲是這個接口的子類
*/
type Interface interface{
	Len() int
	Swap(i,j int ) 
	Less(i,j int)bool
}

func print(data Interface){
	data.Swap(1,2)
	fmt.Println(data)
}

func main() {

	p:= person{"左龍龍", "123"}

	fmt.Println(p.getName())

	s := people{"Zeno", "John", "Al", "Jenny"}
	// fmt.Println(s)
	// print(s)
	// fmt.Println(s)
	// fmt.Println(s)
	// fmt.Println(sort.Reverse(sort.StringSlice(s)))

	// sort.Sort(sort.StringSlice(s))
	// fmt.Println(s)
	// Recover(s)
	// fmt.Println(s)
	 sort.Sort(s)
	// fmt.Println(s)
}
/* 重載,在原有的類型上嵌套一個類型,重置的類型覆寫 */

// https://golang.org/pkg/sort/#Sort
相關文章
相關標籤/搜索