In Go, when a variable is declared it is initialized with zero value as described in the specification.
http://golang.org/ref/spec#The_zero_value
But is it good coding practice to make use of this property and do not explicitly initialize your variable if it needs to initialized with the default value.
for example in the following example
http://play.golang.org/p/Mvh_zwFkOu
package main
import "fmt"
type B struct {
isInit bool
Greeting string
}
func (b *B) Init() {
b.isInit = true
b.Greeting = "Thak you for your time"
}
func (b *B) IsInitialized() bool {
return b.isInit
}
func main() {
var b B
if !b.IsInitialized(){
b.Init()
}
fmt.Println(b.Greeting)
}
The program relies on the default value of boolean to be false.
Variables of any "Object" type (which includes all the classes you will write) have a default value of null. All member variables of a Newed object should be assigned a value by the objects constructor function.
The local variables do not have any default values in Java. This means that they can be declared and assigned a value before the variables are used for the first time, otherwise, the compiler throws an error.
There is no default value for auto variables. global and static variables default to 0, local (auto) variables don't have one.
Set a default valueClick the All tab in the property sheet, locate the Default Value property, and then enter your default value. Press CTRL+S to save your changes.
When a variable is declared it contains automatically the default zero
or null
value for its type: 0
for int
, 0.0
for float
, false
for bool
, empty string for string
, nil
for pointer, zero-ed struct, etc.
All memory in Go is initialized!.
For example: var arr [5]int
in memory can be visualized as:
+---+---+---+---+
| | | | |
+---+---+---+---+
0 1 2 3
When declaring an array, each item in it is automatically initialized with the default zero-value of the type, here all items default to 0.
So preferably it's better to initialize without default value, in other cases than the situations when you explicitly want to declare a variable with a default value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With