search
LoginSignup
1

More than 5 years have passed since last update.

posted at

Organization

Go言語: PHPのarray_combine()のような処理をする関数

どんな振る舞い?

キーのスライスと値のスライスを与えると、マップにして返す関す。例えば、 []string{"green", "red", "yello"}[]string{"avocado", "apple", "banana"} を与えると map[string]string{"green":"avocado", "red":"apple", "yello":"banana"} を返してくる。

main.go
package main

import (
    "log"
    "errors"
)

func arrayCombile(keys []string, values []string) (map[string]string, error) {
    association := map[string]string{}

    if len(keys) != len(values) {
        return association, errors.New("Both parameters should have an equal number of elements")
    }

    for index, key := range keys {
        association[key] = values[index]
    }

    return association, nil
}

func main() {
    a := []string{"green", "red", "yello"}
    b := []string{"avocado", "apple", "banana"}
    c, _ := arrayCombile(a, b)

    log.Printf("%#v", c)
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
1