Sevy
Sevy

Reputation: 300

Can I unpack map values as function arguments?

CreateUser(user, email, password string)
credentials := map[string]string{
    "username": query.Get("username"),
    "password": query.Get("password"),
    "email": query.Get("email"),
  }

userRepository.CreateUser(credentials)

CreateUser function is expecting user, password and email arguments. There's easy way to pass dictionary to a function and "unpack" by adding two stars before variable's name and use each key as name of argument in Python but I can't find answer for Go.

Upvotes: 1

Views: 1291

Answers (1)

Chandan
Chandan

Reputation: 11807

As @BurakSerdar and @icza stated it is not possible in Go to pass spread parameters in function like in Python

You can directly use map[string]string parameter with func

package main

import (
    "fmt"
)

func CreateUser(data map[string]string) {
  fmt.Println(data["username"], data["password"], data["email"])
}

func main() {
    credentials := map[string]string{
        "username": "John",
        "password": "Kenny",
        "email":    "[email protected]",
    }

    CreateUser(credentials)
}

Here working example

Or You can use struct to pass data to func

package main

import (
    "fmt"
)

type User struct {
    Name     string
    Password string
    Email    string
}

func CreateUser(user User) {
    fmt.Println(user.Name, user.Password, user.Email)
}
func main() {
    credentials := User{
        Name: "John",
        Password: "Kenny",
        Email:    "[email protected]",
    }

    CreateUser(credentials)
}

Here working example

Or You can use interface to pass data to func

package main

import (
    "fmt"
)

func CreateUser(m interface{}) {
  data, _ := m.(map[string]string)
  fmt.Println(data["username"], data["password"], data["email"])
}

func main() {
    credentials := map[string]string{
        "username": "John",
        "password": "Kenny",
        "email":    "[email protected]",
    }

    CreateUser(credentials)
}

Here working example

Or You can use array with spread operator to pass data to func

package main

import (
    "fmt"
)

func CreateUser(args ...string) {
    fmt.Println(args[0], args[1], args[2])
}

func main() {

    credentials := map[string]string{
        "username": "John",
        "password": "Kenny",
        "email":    "[email protected]",
    }

    v := make([]string, 0, len(credentials))
    for _, value := range credentials {
        v = append(v, value)
    }

    CreateUser(v...)
}

Here working example

Here's a working example that builds on the User type example above.

Upvotes: 1

Related Questions