Can you use the indefinite parameters of the function?

Time:2022-2-27

If multiple parameters need to be passed in a method and some parameters need not be passed, what should be done?

case

//Newfriend looking for like-minded friends
func NewFriend(sex int, age int, hobby string) (string, error) {
    
    //Logical processing

    return "", nil
}

NewFriend(), parameters in methodsexandageHow to write the method when it is unnecessary to pass parameters?

Use indefinite parameters for parameter transfer!

Think about how to achieve it?

Can you read it like this?

//Sex
type Sex int

//Age
type Age int

//Newfriend looking for like-minded friends
func NewFriend(hobby string, args ...interface{}) (string, error) {
    for _, arg := range args {
        switch arg.(type) {
        case Sex:
            fmt.Println(arg, "is sex")
        case Age:
            fmt.Println(arg, "is age")
        default:
            fmt. Println ("unknown type")
        }
    }
    return "", nil
}

Is there a better plan?

Pass structure Well, this is also a way.

Let’s see how other people’s open source code is written. What I learn isgrpc.Dial(target string, opts …DialOption) Methods, it is throughWithXXMethod, for example:

conn, err := grpc.Dial("127.0.0.1:8000",
    grpc.WithChainStreamInterceptor(),
    grpc.WithInsecure(),
    grpc.WithBlock(),
    grpc.WithDisableRetry(),
)

Compared with the gourd painting ladle, I realized this. You can see:

// Option custom setup config
type Option func(*option)

//Option parameter configuration item
type option struct {
    sex int
    age int
}

//Newfriend looking for like-minded friends
func NewFriend(hobby string, opts ...Option) (string, error) {
    opt := new(option)
    for _, f := range opts {
        f(opt)
    }

    fmt.Println(opt.sex, "is sex")
    fmt.Println(opt.age, "is age")

    return "", nil
}

// WithSex sex 1=female 2=male
func WithSex(sex int) Option {
    return func(opt *option) {
        opt.sex = sex
    }
}

// WithAge age
func WithAge(age int) Option {
    return func(opt *option) {
        opt.age = age
    }
}

This is called when using:

friends, err := friend.NewFriend(
    "Reading",
    friend.WithAge(30),
    friend.WithSex(1),
)

if err != nil {
    fmt.Println(friends)
}

If you add other parameters in this way, is it also easy to configure.

above.

If you have any questions about the above, come to my planet to communicate~ https://t.zsxq.com/iIUVVnA

Recommended Today

Leetcode PHP题解–D127 455. Assign Cookies

D127 455. Assign Cookies topic link 455. Assign Cookies topic analysis Given two arrays, the first array represents the capacity of each container, and the second array represents the number of each item. The items need to be stuffed into the container, but there are two conditions. Condition 1: Only one item can be stuffed […]