MOCKSTACKS
EN
Questions And Answers

More Tutorials








Go Add - Append - Change - Access - Copy Slices

Go Slices like Arrays can be modified changed also can be accessed plus you can copy elements

Append Elements To a Slice

In Go to append and add to slice you can use the syntax append() below is the syntax to append elements to slice

sliceName = append(sliceName, newElement1, newElement2, newElement3, ...)

Example

package main
import ("fmt")

func main() {
  myslice := []int{1, 2, 3, 4, 5}
  fmt.Printf("myslice = %v\n", myslice)
  fmt.Printf("length = %d\n", len(myslice))
  fmt.Printf("capacity = %d\n", cap(myslice))

  myslice = append(myslice, 6, 7, 8, 9, 10)
  fmt.Printf("myslice = %v\n", myslice)
  fmt.Printf("length = %d\n", len(myslice))
  fmt.Printf("capacity = %d\n", cap(myslice))
}

Output

myslice1 = [1 2 3 4 5]
length = 5
capacity = 5
myslice1 = [1 2 3 4 5 6 7 8 9 10]
length = 10
capacity = 10

Change Elements To a Slice

In Go to change an element in Slice using the index of the element similar to Array element Change.

Example

package main
import ("fmt")

func main() {
  mySlice := []int{1,2,3}
  mySlice[2] = 4
  fmt.Println(mySlice[0])
  fmt.Println(mySlice[1])
  fmt.Println(mySlice[2])
}

Output

1
2
4

Copy Elements of a Slice

In Go you can copy elements of slice into another using copy() function which also return the number of copied elements.

Example

package main
import ("fmt")

func main() {
  A := []int{1, 2, 3}
  B := make([]int, 2)
  numberOfCopiedElements := copy(B, A)
  fmt.Println("Copied Slice : ", B)
  fmt.Println("Number of Copied Elements: ", numberOfCopiedElements)
}

Output

Copied Slice : [1 2]
Number of Copied Elements: 2



Conclusion

In this page (written and validated by ) you learned about Go Add - Append - Change - Access - Copy Slices . What's Next? If you are interested in completing Go tutorial, your next topic will be learning about: Go Maps.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.