Posts

Showing posts from December, 2023

Arrays and Slices

Array An array has a fixed size. Since arrays has static size, its memory is allocated only once. If ellipsis "..." is used in-place of size, the length of the array is inferred from the number of values declared.   Syntax var array_name [capacity]type var array_name = [capacity]datatype{values} var array_name = [...]datatype{values} Example var characters := [...]string{"Sheldon", "Leonard", "Wolowitz", "Rajesh"} primes := [5]{2, 3, 5, 7, 11} Slices A slice is dynamically sized. A slice does not store any data. It describes the portion of the underlying array. Changing the elements of the slice modifies the underlying array and other slices that share the same underlying array will also have the changes. A slice literal is similar to an array literal without the length. Internally, it creates the array and builds a slice on top of it. For an array [10]int , the slice equivalents are array[0:10], array[:10], array[0:], array[:] The leng...

Variables and Constants

Variables There are two ways to declare a variable in Golang Use var keyword Use := sign Using var keyword var statement declares a list of variables and it can have  type at the last. var statement can be at a package level or at a function level. Either  type  or  value  is mandate when declaring a variable using  var. Variables can incur the type of the value, if the type is not explicitly specified. Variables declared without values will get initialized with zero value of the type . When type is not specified, multiple values of different types can be initialized in a single var statement. Syntax var name1[, name2, name3, ...] type = value1[, value2, value3, ...] var name1[, name2, name3] type var name = value Example var bookCount, authorCount int = 10, 2 var firstName, lastName string var name, age = "Sheldon", 25 var name = "Sheldon"   Using := sign Variables declared with := sign, often called as short assignment statement, can be us...