Open In App

reflect.ArrayOf() Function in Golang with Examples

Improve
Improve
Like Article
Like
Save
Share
Report

Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.ArrayOf() Function in Golang is used to get the array type with the given count and element type, i.e., if x represents int, ArrayOf(10, x) represents [10]int. To access this function, one needs to imports the reflect package in the program.

Syntax:

func ArrayOf(count int, elem Type) Type

Parameters: This function takes two parameters of int type (count) and Type type(elem).

Return Value: This function returns the array type with the given count and element type.

Below examples illustrate the use of the above method in Golang:

Example 1:




// Golang program to illustrate
// reflect.ArrayOf() Function 
  
package main
  
import (
    "fmt"
    "reflect"
)
  
// Main function 
func main() {
  
    // use of ArrayOf method
    ta := reflect.ArrayOf(5, reflect.TypeOf(123))
    fmt.Println(ta)
}


Output:

[5]int

Example 2:




// Golang program to illustrate
// reflect.ArrayOf() Function 
  
package main
  
import (
    "fmt"
    "reflect"
)
  
// Main function 
func main() {
    t := reflect.TypeOf(5)
      
    // use of ArrayOf method
    arr := reflect.ArrayOf(4, t)
    inst := reflect.New(arr).Interface().(*[4]int)
  
    for i := 1; i <= 4; i++ {
        inst[i-1] = i*i
    }
  
    fmt.Println(inst)
}


Output:

&[1 4 9 16]


Last Updated : 28 Apr, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads