通过 ... 可变参数(适用于相同类型参数)
package main
import "fmt"
func printNames(names ...string) {
if len(names) == 0 {
return
}
for _, name := range names {
fmt.Println("Hello,", name)
}
}
通过 struct 传递选项
package main
import "fmt"
type Config struct {
Name string
Age int
Email string
}
func printInfo(cfg Config) {
fmt.Printf("Name: %s, Age: %d, Email: %s\n", cfg.Name, cfg.Age, cfg.Email)
}
通过 functional options 模式(函数选项式)
package main
import "fmt"
type Config struct {
Name string
Age int
Email string
}
type Option func(*Config)
func WithName(name string) Option {
return func(c *Config) {
c.Name = name
}
}
func WithAge(age int) Option {
return func(c *Config) {
c.Age = age
}
}
func WithEmail(email string) Option {
return func(c *Config) {
c.Email = email
}
}
func NewConfig(opts ...Option) Config {
cfg := Config{Name: "Guest", Age: 18}
for _, opt := range opts {
opt(&cfg)
}
return cfg
}
通过 map 传递参数(适用于动态参数)
package main
import "fmt"
func printInfo(options map[string]interface{}) {
name, _ := options["name"].(string)
age, _ := options["age"].(int)
fmt.Printf("Name: %s, Age: %d\n", name, age)
}