From bf6a10e2cd520a7ee553d913976f08d6eaab5ee4 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 6 Dec 2024 14:45:33 -0600 Subject: [PATCH] Add Combine Two Slices as a Go TIL --- README.md | 3 ++- go/combine-two-slices.md | 51 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 go/combine-two-slices.md diff --git a/README.md b/README.md index 31216c2..e3ba4ca 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1529 TILs and counting..._ +_1530 TILs and counting..._ --- @@ -399,6 +399,7 @@ _1529 TILs and counting..._ - [Access Go Docs Offline](go/access-go-docs-offline.md) - [Build For A Specific OS And Architecture](go/build-for-a-specific-os-and-architecture.md) +- [Combine Two Slices](go/combine-two-slices.md) - [Do Something N Times](go/do-something-n-times.md) - [Find Executables Installed By Go](go/find-executables-installed-by-go.md) - [Not So Random](go/not-so-random.md) diff --git a/go/combine-two-slices.md b/go/combine-two-slices.md new file mode 100644 index 0000000..b280ea7 --- /dev/null +++ b/go/combine-two-slices.md @@ -0,0 +1,51 @@ +# Combine Two Slices + +The `append` function can be used to create a new slice with the contents of +the given slice and one or more items added to the end. + +We can add one or more items like so: + +```go +s1 := []int{1, 2, 3, 4} +s2 := append(s1, 5) +s3 := append(s2, 6, 7, 8) + +fmt.Println(s1) //=> [1 2 3 4] +fmt.Println(s2) //=> [1 2 3 4 5] +fmt.Println(s3) //=> [1 2 3 4 5 6 7 8] +``` + +But what if we have a second slice instead of individual items? We could import +`slices` and use its `Concat` function. Or we can stick with `append` and +unpack that slice as a series of arguments into the second part of `append` +using `slice...`. + +```go +s4 := append(s2, s1...) +fmt.Println(s4) //=> [1 2 3 4 5 1 2 3 4] +``` + +Here is the full example: + +```go +package main + +import ( + "fmt" +) + +func main() { + s1 := []int{1, 2, 3, 4} + s2 := append(s1, 5) + s3 := append(s2, 6, 7, 8) + + fmt.Println(s1) + fmt.Println(s2) + fmt.Println(s3) + + s4 := append(s2, s1...) + fmt.Println(s4) +} +``` + +[source](https://pkg.go.dev/builtin#append)