How to replace all the elements in slice of bytes in Golang?


In Go programming language, slices are a dynamic array that can hold a sequence of elements of the same type. Slices can be created from an array or from another slice. In this article, we will discuss how to replace all the elements in a slice of bytes in Golang.

Replacing elements in a slice of bytes involves iterating over the slice and replacing each element with a new value.

Example

Here's how to do it in Go −

package main

import "fmt"

func main() {
   s := []byte{'h', 'e', 'l', 'l', 'o'}
   fmt.Println("Original slice:", s)

   for i := 0; i < len(s); i++ {
      s[i] = 'x'
   }

   fmt.Println("New slice:", s)
}

Output

Original slice: [104 101 108 108 111]
New slice: [120 120 120 120 120]

In the above example, we create a slice of bytes with the values h, e, l, l, and o. We then iterate over the slice using a for loop and replace each element with the value x. Finally, we print the new slice.

If you want to replace elements in a slice with a different number of elements, you can use the built-in copy() function.

Example

Here's an example −

package main

import "fmt"

func main() {
   s := []byte{'h', 'e', 'l', 'l', 'o'}
   fmt.Println("Original slice:", s)

   newSlice := []byte{'w', 'o', 'r', 'l', 'd'}
   copy(s, newSlice)

   fmt.Println("New slice:", s)
}

Output

Original slice: [104 101 108 108 111]
New slice: [119 111 114 108 100]

In the above example, we create a new slice of bytes with the values w, o, r, l, and d. We then use the copy() function to copy the new slice into the original slice. Since the new slice has the same number of elements as the original slice, all the elements in the original slice are replaced with the new values.

Conclusion

Replacing all the elements in a slice of bytes in Golang can be done by iterating over the slice and replacing each element with a new value or by using the copy() function to replace the original slice with a new slice. Understanding how to manipulate slices in Go is essential for writing efficient and effective code.

Updated on: 26-Apr-2023

208 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements