Sat Dec 30 2023
279 words · 2 minutes

Go接口型函数


Table of Contents

Example Link to Example

GO
1
2
3
4
5
6
7
8
9
type Example interface{
    handle(key int) (int, error)
}

type ExampleFunc func(key int)(int, error)

func(t ExampleFunc) handle(key int)(int, error){
    return t(key)
}

这里定义了一个接口Example ,包含一个方法handle(key int) (int, error) ,然后定义了一个函数类型ExampleFunc,定义了Get方法,并且调用自己,这就是接口型函数。

why Link to why

假如这个GetTest是通过一个接口返回数据,接口类型作为参数,代表数据源.

GO
1
2
3
4
5
6
7
func GetTest(example Example, key int) int{
    if buf, err := example.Get(key); err != nil{
        return nil
    }else{
        return buf
    }
}
方式一: ExampleFunc类型的函数作为参数 Link to 方式一: ExampleFunc类型的函数作为参数
GO
1
2
3
4
5
6
7
8
9
GetTest(ExampleFunc(func(key int) (int, error){
    return int(key), nil
}), 1)

// or
func test(key int) (int, error){
    return int(key), nil
}
GetTest(ExampleFunc(test), 1)
方式二:实现Example接口的结构体 Link to 方式二:实现Example接口的结构体
GO
1
2
3
4
5
type DB struct{params int}
func(db *DB)Query(){}
func(db *DB)Get(key int)(int, error){}

GetTest(new(DB), 1)
Thanks for reading!

Go接口型函数

Sat Dec 30 2023
279 words · 2 minutes

© woshryz | CC BY-SA 4.0