Can you use the indefinite parameters of the function?


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


//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?

type Sex int

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")
            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("",

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 {

    fmt.Println(, "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) { = sex

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

This is called when using:

friends, err := friend.NewFriend(

if err != nil {

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


If you have any questions about the above, come to my planet to communicate~

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 […]