| 1 |
--- |
| 2 |
title: collections.Merge |
| 3 |
description: Returns a map by combining two or more given maps. |
| 4 |
categories: [] |
| 5 |
keywords: [] |
| 6 |
params: |
| 7 |
functions_and_methods: |
| 8 |
aliases: [merge] |
| 9 |
returnType: map[string]any |
| 10 |
signatures: [collections.Merge MAP MAP...] |
| 11 |
aliases: [/functions/merge] |
| 12 |
--- |
| 13 |
|
| 14 |
Returns the result of merging two or more maps from left to right. If a key already exists, `merge` updates its value. If a key is absent, `merge` inserts the value under the new key. |
| 15 |
|
| 16 |
Key handling is case-insensitive. |
| 17 |
|
| 18 |
The following examples use these map definitions: |
| 19 |
|
| 20 |
```go-html-template |
| 21 |
{{ $m1 := dict "x" "foo" }} |
| 22 |
{{ $m2 := dict "x" "bar" "y" "wibble" }} |
| 23 |
{{ $m3 := dict "x" "baz" "y" "wobble" "z" (dict "a" "huey") }} |
| 24 |
``` |
| 25 |
|
| 26 |
Example 1 |
| 27 |
|
| 28 |
```go-html-template |
| 29 |
{{ $merged := merge $m1 $m2 $m3 }} |
| 30 |
|
| 31 |
{{ $merged.x }} → baz |
| 32 |
{{ $merged.y }} → wobble |
| 33 |
{{ $merged.z.a }} → huey |
| 34 |
``` |
| 35 |
|
| 36 |
Example 2 |
| 37 |
|
| 38 |
```go-html-template |
| 39 |
{{ $merged := merge $m3 $m2 $m1 }} |
| 40 |
|
| 41 |
{{ $merged.x }} → foo |
| 42 |
{{ $merged.y }} → wibble |
| 43 |
{{ $merged.z.a }} → huey |
| 44 |
``` |
| 45 |
|
| 46 |
Example 3 |
| 47 |
|
| 48 |
```go-html-template |
| 49 |
{{ $merged := merge $m2 $m3 $m1 }} |
| 50 |
|
| 51 |
{{ $merged.x }} → foo |
| 52 |
{{ $merged.y }} → wobble |
| 53 |
{{ $merged.z.a }} → huey |
| 54 |
``` |
| 55 |
|
| 56 |
Example 4 |
| 57 |
|
| 58 |
```go-html-template |
| 59 |
{{ $merged := merge $m1 $m3 $m2 }} |
| 60 |
|
| 61 |
{{ $merged.x }} → bar |
| 62 |
{{ $merged.y }} → wibble |
| 63 |
{{ $merged.z.a }} → huey |
| 64 |
``` |
| 65 |
|
| 66 |
> [!NOTE] |
| 67 |
> Regardless of depth, merging only applies to maps. For slices, use the [`collections.Append`][] function. |
| 68 |
|
| 69 |
[`collections.Append`]: /functions/collections/append/ |