Day5: Short variables declaration and Naming Rules

We mentioned that you can declare variables and assign them values on the same line: But if you know what the initial value of a variable is going to be as soon as you declare it, it’s more typical to use a short variable declaration. Instead of explicitly declaring the type of the variable and later assigning to it with =, you do both at once using :=

var quantity init = 10
var length, width float64 = 1.5, 2.5
var customerName string = "Nielsen"

Sample Code:

package main

import "fmt"

var quantity int = 4
var length, width = 1.5, 2.4
var customerName = "Nielsen"

func main() {
    fmt.Println(customerName)
    fmt.Println("has ordered", quantity, "sheets")
    fmt.Println("each with an area of")
    fmt.Print(length*width, "square meters")
}

Short Variables declaration

quantity :=4
length, width := 1.5,2.5
customerName := "Nielsen"

Sample Code:

package main

import "fmt"

func main() {
    quantity := 4
    length, width := 1.5, 2.4
    customerName := "Nielsen"
    fmt.Println(customerName)
    fmt.Println("has ordered", quantity, "sheets")
    fmt.Println("each with an area of")
    fmt.Print(length*width, "square meters")
}

There’s no need to explicitly declare the variable’s type; the type of the value assigned to the variable becomes the type of that variable. Because short variable declarations are so convenient and concise, they’re used more often than regular declarations. You’ll still see both forms occasionally, though, so it’s important to be familiar with both.

Naming Rules:

Go has one simple set of rules that apply to the names of variables, functions, and types:

  • A name must begin with a letter, and can have any number of additional letters and numbers.

  • If the name of a variable, function, or type begins with a capital letter, it is considered exported and can be accessed from packages outside the current one. (This is why the P in fmt.Println is capitalized: so it can be used from the main package or any other.) If a variable/function/type name begins with a lowercase letter, it is considered unexported and can only be accessed within the current package.