How to merge two slices in Go? Slice concatenation
Hello! I just started learning Go and ran into a problem. I need to merge two slices into one. In Python I would just write `list1 + list2`, but in Go, as I understand, there is no such operation.
I have two slices of integers:
```go
slice1 := []int{1, 2, 3}
slice2 := []int{4, 5, 6}
```
I want to get the result: `[1 2 3 4 5 6]`. I tried using the `+` operator, but the compiler gives an error: `invalid operation: slice1 + slice2 (operator + not defined on slice)`.
Then I came across the `append` function, but it adds elements one by one. Writing a loop for each element — isn't that inefficient? Maybe there is some built-in way or idiomatic solution in Go? Also, another question: if I use `append`, will it affect the original slices? Will the new slice be independent?
No answers yet.
Log in to leave an answer
Blogs
GraphQL API with PHP: Step-by-Step Tutorial for Beginners
Docker and TypeScript: Advanced Application Containerization
How the Rust Debugger Works Under the Hood: A Step-by-Step Breakdown
Error Localization in Swift: How to Make Error Understandable to the User