1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

どんな振る舞い?

キーのスライスと値のスライスを与えると、マップにして返す関す。例えば、 []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)
}

1
1
0

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
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?