golang实现默认参数的方式

golang实现默认参数的方式

package main

import (
    "fmt"
    "time"
)

func main() {
    options := []reqOption{
        setTimeoutOption(time.Second),
        setHttpsOption(true),
    }
    doReq("123", 123, options...)
}

type reqParam struct {
    ip      string
    port    int32
    timeout time.Duration
    https   bool
}

func setTimeoutOption(t time.Duration) reqOption {
    return func(param *reqParam) {
        param.timeout = t
    }
}

func setHttpsOption(useHttps bool) reqOption {
    return func(param *reqParam) {
        param.https = useHttps
    }
}

type reqOption func(param *reqParam)

func doReq(ip string, port int32, options ...reqOption) {
    var rp = reqParam{
        ip:      ip,
        port:    port,
        timeout: 0,
        https:   true,
    }
    for _, o := range options {
        o(&rp)
    }
    fmt.Println(rp.timeout)
}

你可能感兴趣的:(golang实现默认参数的方式)