关于interface
一、interface更多的作用是用于规范和协助分工。
比如:
1、统筹方定义了一组接口:里面需要实现3个方法a(),b(),c();
2、组1需要实现该接口,以实现f功能
3、组2需要实现该接口,以实现g功能,f和g功能都遵循接口定义的规范。比如接口是电脑,组1实现的是手机用usb接入,组2实现的是相机用usb接入。
二、interface也可以用来开放功能接口
1、只要你满足我接口的参数的要求(比如参数需要实现接口的方法)比如:sort.Sort(I interface),一般I是指针,然后就可以返回I对应的计算结果后的结果
2、业务方只需要实现I简单的接口方法,然后调用功能接口的方法,即可实现响应高难度的逻辑。(Sort里面有复杂的业务逻辑,只要满足I接口类型的参数,都可以调用)
demo:
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sort_test
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
func (p Person) String() string {
return fmt.Sprintf("%s: %d", p.Name, p.Age)
}
// ByAge implements sort.Interface for []Person based on
// the Age field.
type ByAge []Person
func (a ByAge) Len() int { return len(a) }
func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func Example() {
people := []Person{
{"Bob", 31},
{"John", 42},
{"Michael", 17},
{"Jenny", 26},
}
fmt.Println(people)
// There are two ways to sort a slice. First, one can define
// a set of methods for the slice type, as with ByAge, and
// call sort.Sort. In this first example we use that technique.
sort.Sort(ByAge(people))
fmt.Println(people)
// The other way is to use sort.Slice with a custom Less
// function, which can be provided as a closure. In this
// case no methods are needed. (And if they exist, they
// are ignored.) Here we re-sort in reverse order: compare
// the closure with ByAge.Less.
sort.Slice(people, func(i, j int) bool {
return people[i].Age > people[j].Age
})
fmt.Println(people)
// Output:
// [Bob: 31 John: 42 Michael: 17 Jenny: 26]
// [Michael: 17 Jenny: 26 Bob: 31 John: 42]
// [John: 42 Bob: 31 Jenny: 26 Michael: 17]
}
暗夜之中,才见繁星;危机之下,暗藏转机;事在人为,为者常成。

浙公网安备 33010602011771号