Variables

·

2 min read

Declaring A Variable

  • Variables are declared using the var keyword

  • If not assigning any value to a variable, the value of an initialized variable with no assignment will be zero value.

  •     var number int
    
        var pi float64 = 3.14159
    

Basic Go Variable Types

bool

string

int  int8  int16  int32  int64
uint uint8 uint16 uint32 uint64 uintptr

byte // alias for uint8

rune // alias for int32
     // represents a Unicode code point

float32 float64

complex64 complex128

Short Variable Declaration

  • Inside a function (even in the main function), the := can be used in place of a var declaration.

  • The := operator infers the type of the new variable based on the value.

  • Outside of a function, every statement should begin with a keyword like var, const, func, and so on.

// the same
var empty string
empty := ""
// inferred to be an integer
numberOfCars := 10

// inferred to be an floating point
temperature := 0.0 

// inferred to be a boolean
var isFunny = true
  • We can declare multiple variables on the same line
date, isMonday := "2023/05/30", false

Which Type Should I Use?

  • Always stick to these type:
bool
string
int
uint
byte
rune
float64
complex128

Reference: