DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for How to make variables without assigning values in Go or Golang?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to make variables without assigning values in Go or Golang?

#go

Originally posted here!

To make variables without assigning values in Golang, you can use the var keyword followed by the variable name you wish to give and then the type of the value that you wish to hold in the variable.

TL;DR

package main

import "fmt"

// make a variable but do
// not assign a value now
var name string

func main() {
    // assign a value to the `name`
    // variable using the `=` operator
    name = "John Doe"

    // log the `name` variable
    // value to console
    fmt.Print(name) // John Doe
}
Enter fullscreen mode Exit fullscreen mode

For example, let's say we need to make a variable called name but we do not need to assign a value to it right away.

It can be done like this,

package main

// make a variable but do
// not assign a value now
var name string
Enter fullscreen mode Exit fullscreen mode

Now to assign a value to it we can use the = operator (equal symbol) after the variable name, in our case it is name and then after the = symbol, we can write the value that needs to be assigned to it.

It can be done like this,

package main

// make a variable but do
// not assign a value now
var name string

func main() {
    // assign a value to the `name`
    // variable using the `=` operator
    name = "John Doe"
}
Enter fullscreen mode Exit fullscreen mode

NOTE: When assigning a value to a variable in Go, you need to make sure it is inside a function or it will throw an error

Finally, let's print the variable name value to the console using the Print() method from the fmt standard package in Go like this,

package main

import "fmt"

// make a variable but do
// not assign a value now
var name string

func main() {
    // assign a value to the `name`
    // variable using the `=` operator
    name = "John Doe"

    // log the `name` variable
    // value to console
    fmt.Print(name) // John Doe
}
Enter fullscreen mode Exit fullscreen mode

We have successfully made a variable without assigning a value in Go. Yay πŸ₯³!

See the above code live in The Go Playground.

That's all πŸ˜ƒ.

Feel free to share if you found this useful πŸ˜ƒ.


Top comments (1)

Collapse
 
vitalipom profile image
Vitali Pomanitski • Edited on

Dear Melvin, could you create a single one-page long tutorial out of those mid length posts? It spams a bit and perceived negatively in most of the cases. I can send you an example of β€œlong” tutorial that has made a history in here if you want.

🌚 Life is too short to browse without dark mode