Today I Learned Series: Copy between two Slices/Array in Golang

Part of Today I Learn Series in Easyread

Today, I learned some weird unique and cool things in Golang.

It happen when I want to move an Object to first of Array in golang.

func sample(){
number:=9
arr:= []int{ 1,2,3,4,5}
}

What I want to achieve is, I want to append the number : 9 to the first index of array

arr:=[]int{9,1,2,3,4,5}

Then, based on my experience in programming, I could make this with making a new array, then copy the value using looping.

func sample(){
number:=9
arr:= []int{ 1,2,3,4,5}
arrNew:= make([]int, len(arr) +1 )
 for i:=0 ;i< (len(arr)+1) ; i++ {
if i==0 {
arrNew[i] = number
}else{
arrNew[i]=arr[i-1]
}
}
fmt.Println(arrNew)
}
// Print: [ 9,1,2,3,4,5]

Well that’s how classic works. But, until I found the slice feature, I can do it will more simpler :

func sample(){
number:=9
arr:= []int{ 1,2,3,4,5}
arrNew:= make([]int,0)
arrNew= append(arrNew,number)
arrNew= append(arrNew,arr...)
fmt.Println(arrNew)
}
// Print: [ 9,1,2,3,4,5]

Or another sample

func sample(){
number:=9
arr:= []int{ 1,2,3,4,5}
arrNew:= make([]int,len(arr)+1)
arrNew[0]= number
arrNew= append(arrNew[:1],arr...)
fmt.Println(arrNew)
}
// Print: [ 9,1,2,3,4,5]

Well, It’s help and reduce length of the code line. This feature make me more loved to use golang.


One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.