Home > Mobile >  Variable declaration in Golang (new keyword)
Variable declaration in Golang (new keyword)

Time:12-08

When writing a go code i see there are 2 options to declare variable

I wonder what are the differences of these?

And in the second way as i know lock is initialized as nil defaut value, how can it access the method inside it like lock.Lock without error?]

var lock := new(sync.Mutex)

var lock sync.Mutex

CodePudding user response:

if you run this program

    var i int  // line 1
    var pi = new(int)  // line 2
    fmt.Printf("%T,%T", i, pi)

you would get the following output:

int,*int

%T prints the variable's type.

In line 1, var allocates storage to the variable, binds it to an identifier e.g., i and initialize it to the zero value of its type. In line 2, var with new() does the same thing but it returns a pointer to the storage allocated to the variable.

In both cases, the variable is initialized to its zero value. Whether it is valid to use such a zero-initialized variable, depends on its implementation. In idiomatic Go, a zero-initialized variable is often usable, but that is not always possible.

  •  Tags:  
  • go
  • Related