加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang:接口(interface)

发布时间:2020-12-16 09:30:05 所属栏目:大数据 来源:网络整理
导读:Go中没有class的概念。Go 语言中使用组合实现对象特性的描述。对象的内部使用结构体内嵌组合对象应该具有的特性,对外通过接口暴露能使用的特性。 Go 语言的接口设计是非侵入式的,接口不知道接口被哪些类型实现。而实现不用指明具体实现哪一个接口。编译时


Go中没有class的概念。Go 语言中使用组合实现对象特性的描述。对象的内部使用结构体内嵌组合对象应该具有的特性,对外通过接口暴露能使用的特性。
Go 语言的接口设计是非侵入式的,接口不知道接口被哪些类型实现。而实现不用指明具体实现哪一个接口。编译时时编译器会指明使用哪个类型实现哪个接口。

只有让接口和实现解耦,编译速度才能真正提高,项目之间的耦合度也会降低不少。 很多其他语言实现接口时,是必须指定接口的。

?

实现接口

只有接口的方法名,参数,返回值都在某一类型中对应上,我们才说这个类型实现了接口。

 1 package main
 2 
 3 import (
 4     "fmt"
 5 )
 6 
 7 // interface
 8 type Animal interface {
 9     Cry(data interface{}) error
10 }
11 
12 // stuct
13 type Cat struct {
14 }
15 
16 func (cat *Cat) Cry(data interface{}) error {
17     fmt.Println("Mi:",data)
18     return nil
19 }
20 func main() {
21     cat := new(Cat)
22     var animal Animal
23     animal = cat
24     animal.Cry("Ao")
25 }

在16行Cat实现了Animal的唯一方法,所以在23,14行我们可以使用animal调用cat的方法。

?sort.Interface


sort.interface是Go内置的一个帮助排序的接口。接口的定义如下

 1 // A type,typically a collection,that satisfies sort.Interface can be
 2 // sorted by the routines in this package. The methods require that the
 3 // elements of the collection be enumerated by an integer index.
 4 type Interface interface {
 5     // Len is the number of elements in the collection.
 6     Len() int
 7     // Less reports whether the element with
 8     // index i should sort before the element with index j.
 9     Less(i,j int) bool
10     // Swap swaps the elements with indexes i and j.
11     Swap(i,j int)
12 }

其中包含排序需要的:数量(Len)、比较(Less)、交换(Swap)

实现接口

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "sort"
 6 )
 7 
 8 type IntList []int
 9 
10 func (i IntList) Len() int {
11     return len(i)
12 }
13 func (i IntList) Less(a,b int) bool {
14     return i[a]%10 < i[b]%10
15 }
16 func (i IntList) Swap(a,b int) {
17     i[a],i[b] = i[b],i[a]
18 }
19 func main() {
20     ints := IntList{3,14,1,45,37,22,85,19}
21     sort.Sort(ints)
22     for _,v := range ints {
23         fmt.Printf("%sn",v)
24     }
25 }

?

这个代码并不复杂,主要看清除4行即可。打印结果

%!s(int=1)
%!s(int=22)
%!s(int=3)
%!s(int=14)
%!s(int=45)
%!s(int=85)
%!s(int=37)
%!s(int=19)

?使用sort.Slice进行切片元素排序

?sort.Slice() 函数进行更为简便的排序方法,把上面的代码稍微整理之后:

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "sort"
 6 )
 7 
 8 type IntList []int
 9 
10 func main() {
11     ints := IntList{3,19}
12     sort.Slice(ints,func(i,j int) bool {
13 
14         return ints[i]%10 < ints[j]%10
15     })
16     for _,v := range ints {
17         fmt.Printf("%sn",v)
18     }
19 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读