S
S
stasboiko2021-11-05 01:17:25
go
stasboiko, 2021-11-05 01:17:25

How to correctly pass multiple parameters to a function in Golang?

I need to pass many parameters to a function, like this:

user, err := CreateUser(r.Context(), body.Name, body.Email, body.FirstName, body.LastName,
    body.Birthday, body.Phone, body.Gender, body.Password, body.Status)

It looks terrible + the Go documentation says that no more than 4 parameters should be passed/received in functions.
How to do it correctly/beautifully?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Mamonov, 2021-11-05
@stasboiko

In such cases, it is better to pass the structure as a parameter.
Example

type User struct {
    Name string
    Email string
    // все нужные поля далее
}

func CreateUser(r.Context(), user)

N
nakem, 2021-11-05
@nakem

In some cases, functional options may be more appropriate.
Dave Cheney wrote about this in detail https://dave.cheney.net/2014/10/17/functional-opti...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question