Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang: Set type struct to nil [closed]

Tags:

go

type Ptr struct {
    ID   *big.Int
    IpAddress string
    Port      string
}
var NewVar Ptr

After initializing the NewVar with values I then want to set NewVar to nil. How can I do this?

like image 337
wwjdm Avatar asked May 08 '15 19:05

wwjdm


People also ask

Can Go structs be nil?

nil is not an allowed value for a struct. It is however, a common value for a pointer.

How do I assign nil in Golang?

To actually be able to assign a new value ( nil ) to the pointer variable, we have to dereference it ( * operator).

Is nil null in Go?

About nil. nil is a predefined identifier in Go that represents zero values of many types. nil is usually mistaken as null (or NULL) in other languages, but they are different. Note: nil can be used without declaring it.

What is nil in Go lang?

In the Go programming language, nil is a zero value. Recall from unit 2 that an integer declared without a value will default to 0. An empty string is the zero value for strings, and so on. A pointer with nowhere to point has the value nil .


1 Answers

The zero value of a struct value is not nil

Each element of such a variable or value is set to the zero value for its type: false for booleans, 0 for integers, 0.0 for floats, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps.

In your case, this variable declaration var NewVar Ptr creates the variable, binds corresponding identifier Ptr to it, and gives it a type and an initial value.

like image 154
VonC Avatar answered Oct 09 '22 10:10

VonC