Friday, March 24, 2023

How To Convert Array to Slice in Go Language

Array is a fixed in size and can't be increased/decreased the size at run time where as Slices are dynamic in nature like can be decreased or increased the size automatically at runtime basis on the number of elements added to it.

To convert the array to slice at anytime we can use simply :(dot notation) shown in below


Source Code:

package main

import (
	"fmt"
	"reflect"
)

func main() {
	arr := [4]string{"go", "lang", "main", "sree"}
	fmt.Println("Arr is of type...", reflect.TypeOf(arr))
	arr2 := arr[:]   //Converts arr of type array to slice arr2
	fmt.Println("Arr2 is of type..", reflect.TypeOf(arr2))
}

Output:

Arr is of type... [4]string
Arr2 is of type.. []string




Please comment or write us if you have any queries/requirements.

Please like,follow,bookmark,subscribe this site to receive daily updates.


FaceBook Page - I Love Coding. You?


Hope this helps you..Enjoy..!




No comments:

Post a Comment