go 使用options扩展参数

package main

import (
	"fmt"
)

type Config struct {
	path      string
	isUseFile bool
}

type ConfigOption func(config *Config) error

func WithPath(path string) ConfigOption {
	return func(config *Config) error {
		if path == "" {
			return fmt.Errorf("path is empty")
		}
		config.path = path
		return nil
	}
}

func WithUseFile(isUseFile bool) ConfigOption {
	return func(config *Config) error {
		config.isUseFile = isUseFile
		return nil
	}
}

func NewConfig(opts ...ConfigOption) (*Config, error) {
	var config *Config = &Config{}

	for _, opt := range opts {
		if err := opt(config); err != nil {
			return config, err
		}
	}
	return config, nil
}

func main() {
	config, err := NewConfig(WithPath("123"), WithUseFile(false))
	fmt.Printf("path:%s isUseFile:%v err:%v\n", config.path, config.isUseFile, err)
}

posted on 2025-06-22 16:17  王景迁  阅读(7)  评论(0)    收藏  举报

导航