Golang之可选参数模式


Go 不支持像 Python、JavaScript 那样的“默认参数”,因此通常有以下三种可选参数编码模式,适合用于封装 gRPC 客户端、工具库或模块组件时的配置初始化。

方式一:直接传入多个参数

type Client struct {
    Host string
    Port int
}

func NewClient(host string, port int) *Client {
    return &Client{Host: host, Port: port}
}

client := NewClient("localhost", 50051)

适用于参数很少或明确的情况。
缺点:参数一多就难维护,不易拓展。

方式二:传入配置 struct(Option Struct)

type ClientOptions struct {
    Host string
    Port int
    Token string
}

type Client struct {
    opts ClientOptions
}

func NewClient(opts ClientOptions) *Client {
    return &Client{opts: opts}
}

// 调用
client := NewClient(ClientOptions{
    Host:  "localhost",
    Port:  50051,
    Token: "abc123",
})

推荐用于结构清晰、参数数量中等的情况。
优点:
参数具名,扩展性强
不怕参数顺序出错

方式三:函数式选项(Functional Options Pattern)

Go 社区推荐的一种灵活配置方式,适用于参数众多、希望可选参数更灵活的场景。

type Client struct {
    host  string
    port  int
    token string
}

type Option func(*Client)

func WithHost(h string) Option {
    return func(c *Client) {
        c.host = h
    }
}

func WithToken(t string) Option {
    return func(c *Client) {
        c.token = t
    }
}

func NewClient(opts ...Option) *Client {
    c := &Client{
        host: "127.0.0.1",
        port: 50051,
    }
    for _, opt := range opts {
        opt(c)
    }
    return c
}

// 使用方式
client := NewClient(
    WithHost("grpc.server.local"),
    WithToken("my-token"),
)

优点:
可选、顺序不敏感
支持默认值
易于封装中间件、客户端构建器(builder)

本文地址:https://www.blear.cn/article/golang-option-params

转载时请以链接形式注明出处

评论
受监管部门要求,个人网站不允许评论功能,评论已关闭,抱歉!