Skip to content
Related Articles

Related Articles

reflect.ArrayOf() Function in Golang with Examples
  • Last Updated : 28 Apr, 2020

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
}

chevron_right


Output:

[5]int

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
}

chevron_right


Output:

&[1 4 9 16]
My Personal Notes arrow_drop_up
Recommended Articles
Page :