Golang中如何为函数参数设置默认值

Golang中如何为函数参数设置默认值 有没有办法为函数参数设置默认值 例如:

func sm(x float64, mu float64 = 2) (float64, float64) {
return (x, mu)
}
x := 1
s := sm(x)
// 返回 (1, 2)
5 回复

感谢Norbert和Ashish

更多关于Golang中如何为函数参数设置默认值的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


只要所有参数都是同一类型,同样的技术就适用。

不过我认为这是一种权宜之计。

只需使用具有不同参数集的不同命名函数即可。

如果有多个默认参数怎么办?

例如,不使用:func sm(x float64, mu float64 = 2) 而使用这个定义:func sm(x float64, mu float64 = 2, sigma float64 = 3)

有时希望用用户提供的值来更改这些默认值。

遗憾的是,Go 语言不支持默认参数。但是,你可以基于可变参数函数来定义你的方法。

你上面的例子可以这样写:

// 一个棘手的情况可能是当你这样做时
// func sm(args ...float64) (float64, float64) {} 这里人们
// 可以像这样调用你的函数 sm(),这并不
// 满足你上面提到的函数设计
// 所以我们这样定义它
func sm(x float64, args ...float64) (float64, float64) {
mu := 2
if len(args) > 0 {
    mu = args[0]
}

return (x, mu)
}

在Go语言中,函数参数不支持直接设置默认值。不过,可以通过以下几种方式实现类似功能:

1. 使用结构体参数(推荐)

type Config struct {
    X  float64
    Mu float64
}

func NewConfig() Config {
    return Config{
        X:  0,
        Mu: 2, // 默认值
    }
}

func sm(cfg Config) (float64, float64) {
    return cfg.X, cfg.Mu
}

// 使用
cfg := NewConfig()
cfg.X = 1
result := sm(cfg) // 返回 (1, 2)

2. 使用可变参数(variadic parameters)

func sm(x float64, mu ...float64) (float64, float64) {
    defaultMu := 2.0
    if len(mu) > 0 {
        defaultMu = mu[0]
    }
    return x, defaultMu
}

// 使用
result1 := sm(1)        // 返回 (1, 2)
result2 := sm(1, 3.5)   // 返回 (1, 3.5)

3. 使用函数选项模式(Functional Options Pattern)

type SMOptions struct {
    mu float64
}

type Option func(*SMOptions)

func WithMu(mu float64) Option {
    return func(o *SMOptions) {
        o.mu = mu
    }
}

func sm(x float64, opts ...Option) (float64, float64) {
    options := &SMOptions{
        mu: 2, // 默认值
    }
    
    for _, opt := range opts {
        opt(options)
    }
    
    return x, options.mu
}

// 使用
result1 := sm(1)                    // 返回 (1, 2)
result2 := sm(1, WithMu(3.5))       // 返回 (1, 3.5)
result3 := sm(1, WithMu(4), WithMu(5)) // 返回 (1, 5)

4. 使用多个函数

func sm(x float64, mu float64) (float64, float64) {
    return x, mu
}

func smWithDefault(x float64) (float64, float64) {
    return sm(x, 2)
}

// 使用
result1 := sm(1, 2)        // 显式指定
result2 := smWithDefault(1) // 使用默认值

最常用的是结构体参数和函数选项模式,它们提供了更好的可读性和扩展性。

回到顶部