Creating new values

The reflect package allows us also to create new values using types. There are several functions that allow us to create a value:

  • MakeChan creates a new channel value
  • MakeFunc creates a new function value
  • MakeMap and MakeMapWithSize creates a new map value
  • MakeSlice creates a new slice value
  • New creates a new pointer to the type
  • NewAt creates a new pointer to the type using the selected address
  • Zero creates a zero value of the selected type

The following code shows how to create new values in a couple of different ways:

func main() {
t := reflect.TypeOf(int64(100))
// zero value
fmt.Printf("%#v ", reflect.Zero(t))
// pointer to int
fmt.Printf("%#v ", reflect.New(t))
}

A full example is available here: https://play.golang.org/p/wCTILSK1F1C.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.148.210