Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it required to assign default value to variable?

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.

like image 613
Mayank Patel Avatar asked Jul 23 '15 08:07

Mayank Patel


People also ask

What default value is assigned to a variable?

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.

Which variables have no default values?

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.

Is Auto requires you to assign an initial value state yes or no?

There is no default value for auto variables. global and static variables default to 0, local (auto) variables don't have one.

Where should set the default values?

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.


1 Answers

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.

like image 96
Endre Simo Avatar answered Oct 16 '22 22:10

Endre Simo