DEV Community

Cover image for What are the initial values assigned to variables with types in Go or Golang?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

What are the initial values assigned to variables with types in Go or Golang?

#go

Originally posted here!

In Go or Golang, once you declare a variable using the var keyword and its corresponding type the compiler assigns an initial value to it according to the variable's type.

string type values

For string type values the initial value assigned to it is an empty string ("").

To check let's first create a string type variable using the var keyword and then simply print the value of that variable to the console.

It can be done like this,

// declare a `string` type variable
var name string

fmt.Println(name) // ""
Enter fullscreen mode Exit fullscreen mode

numeric type values

For numeric type values (int, uint, and float types) the initial value assigned to it is 0.

To check let's first create an int type variable using the var keyword and then simply print the value of that variable to the console.

It can be done like this,

// declare a `int` type variable
var num int

fmt.Println(num) // 0
Enter fullscreen mode Exit fullscreen mode

bool type values

For bool type values the initial value assigned to it is false.

To check let's first create a bool type variable using the var keyword and then simply print the value of that variable to the console.

It can be done like this,

// declare a `bool` type variable
var isAdmin bool

fmt.Println(isAdmin) // false
Enter fullscreen mode Exit fullscreen mode

See the above codes live in The Go Playground.

That's all 😃!

Feel free to share if you found this useful 😃.


Top comments (0)