func (db *DB) Query(query string, args ...interface{}) (*Rows, error)
func (db *DB) QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error)
func (db *DB) Query(query string, args ...interface{}) (*Rows, error) {
return db.QueryContext(context.Background(), query, args...)
}
func Dial(network, addr string, config *Config) (*Conn, error)
func Listen(network, address string) (Listener, error)
type ListenConfig struct {
Control func(network, address string, c syscall.RawConn) error
}
func (*ListenConfig) Listen(ctx context.Context, network, address string) (Listener, error)
package main
import "fmt"
// 选项设计模式
// 问题:有一个结构体,定义一个函数,给结构体初始化
// 结构体
type Options struct {
str1 string
str2 string
int1 int
int2 int
}
// 声明一个函数类型的变量,用于传参
type Option func(opts *Options)
func InitOptions(opts ...Option) {
options := &Options{}
for _, opt := range opts {
opt(options)
}
fmt.Printf("options:%#v\n", options)
}
func WithStringOption1(str string) Option {
return func(opts *Options) {
opts.str1 = str
}
}
func WithStringOption2(str string) Option {
return func(opts *Options) {
opts.str2 = str
}
}
func WithStringOption3(int1 int) Option {
return func(opts *Options) {
opts.int1 = int1
}
}
func WithStringOption4(int1 int) Option {
return func(opts *Options) {
opts.int2 = int1
}
}
func main() {
InitOptions(WithStringOption1("5lmh.com"), WithStringOption2("topgoer.com"), WithStringOption3(5), WithStringOption4(6))
}
前言: 功力未够,不能充分吸收。后续会完善
需要在方法中添加新参数。直接修改原来的方法有风险
添加新方法,旧方法引用新方法
Query需要添加context参数
新建QueryContext方法,Query方法调用QueryContext方法
如果能预料到未来可能需要更多的参数,函数参数最好是可选的。例如将结构体作为参数
可以通过扩展结构体的方式扩展新方法
Listen方法需要添加context参数
考虑到Listen还会有变更的可能性,新建ListenConfig结构体并扩展Listen方法
选项设计模式("Option types"),grpc频繁用到
如何在接口上实现新方法
类型判断
引用
Keeping Your Modules Compatible