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
}
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
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"
}
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
}
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 😃.
Top comments (0)