Go new operator

Introduction

Another way to get a pointer is to use the built-in new function:

package main/*w w  w.  j  a  v a  2  s  .c o m*/

import "fmt"
func one(xPtr *int) { 
    *xPtr = 1 
} 

func main() { 
    xPtr  := new(int) 
    one(xPtr) 
    fmt.Println(*xPtr) // x is 1 
} 

Go new operator does three things:

  • takes a type as an argument
  • allocates enough memory to fit a value of that type
  • returns a pointer to it.



PreviousNext

Related