Variables and constants
Variables are spaces in computer's memory to store values that can be modified during the execution of the program. Variables and constants have a type like the ones described in preceding text. Although, you don't need to explicitly write the type of them (although you can do it). This property to avoid explicit type declaration is what is called Inferred types. For example:
//Explicitly declaring a "string" variable var explicit string = "Hello, I'm a explicitly declared variable"
Here we are declaring a variable (with the keyword var
) called explicit
of string type. At the same time, we are defining the value to Hello World!
.
//Implicitly declaring a "string". Type inferred inferred := ", I'm an inferred variable "
But here we are doing exactly the same thing. We have avoided the var
keyword and the string
type declaration. Internally, Go's compiler will infer (guess) the type of the variable to a string type. This way you have to write much less code for each variable definition.
The following lines use the reflect
package to gather information about a variable. We are using it to print the type of (the TypeOf
variable in the code) of both variables:
fmt.Println("Variable 'explicit' is of type:", reflect.TypeOf(explicit)) fmt.Println("Variable 'inferred' is of type:", reflect.TypeOf(inferred))
When we run the program, the result is the following:
$ go run main.go Hello, I'm a explicitly declared variable Hello, I'm an inferred variable Variable 'explicit' is of type: string Variable 'inferred' is of type: string
As we expected, the compiler has inferred the type of the implicit variable to string too. Both have written the expected output to the console.