Basics Flashcards

To learn basics of golang

1
Q

What does “package main” mean?

A

It lets the Go compiler know that we want this code to compile and run as a standalone program, as opposed to being a library that’s imported by other programs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

import “fmt”?

A

It imports the fmt (formatting) package from the standard library. It allows us to use fmt.Println to print to the console.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What’s “func main()”

A

It defines the main function, the entry point for a Go program.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Generally speaking, there are two kinds of errors in programming:

A

Compilation errors: Occur when code is compiled. It’s generally better to have compilation errors because they’ll never accidentally make it into production. You can’t ship a program with a compiler error because the resulting executable won’t even be created.

Runtime errors: Occur when a program is running. These are generally worse because they can cause your program to crash or behave unexpectedly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Go code generally runs ____ than interpreted languages and compiles ____ than other compiled languages

A

faster, faster - Go programs don’t run quite as fast as its compiled Rust, Zig, and C counterparts. That said, it compiles much faster than they do, which makes the developer experience super productive. Unfortunately, there are no swordfights on Go teams…

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Convert to int
temperatureFloat := 88.26

A

temperatureInt := int(temperatureFloat)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Rune in Golang

A

In the past, we only had one character set, and that was known as ASCII (American Standard Code for Information Interchange). There, we used 7 bits to represent 128 characters, including upper and lowercase English letters, digits, and a variety of punctuations and device-control characters. Due to this character limitation, the majority of the population is not able to use their custom writing systems. To solve this problem, Unicode was invented. Unicode is a superset of ASCII that contains all the characters present in today’s world writing system. It includes accents, diacritical marks, control codes like tab and carriage return, and assigns each character a standard number called “Unicode Code Point”, or in Go language, a “Rune”. The Rune type is an alias of int32. Important Points:

Always remember, a string is a sequence of bytes and not of a Rune. A string may contain Unicode text encoded in UTF-8. But, the Go source code encodes as UTF-8, therefore, no need to encode the string in UTF-8.

UTF-8 encodes all the Unicode in the range of 1 to 4 bytes, where 1 byte is used for ASCII and the rest for the Rune.

ASCII contains a total of 256 elements and out of which, 128 are characters and 0-127 are identified as code points. Here, code point refers to the element which represents a single value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Recommended default types in go

A

When Go developers stray from the “default” type for any given type family, the code can get messy quickly. Unless you have a good performance related reason, you’ll typically just want to use the “default” types:

bool
string
int
uint
byte
rune
float64
complex128

When should I use a more specific type?
When you’re super concerned about performance and memory usage.

That’s about it. The only reason to deviate from the defaults is to squeeze out every last bit of performance when you are writing an application that is resource-constrained. (Or, in the special case of uint64, you need an absurd range of unsigned integers).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Explain “Go is Statically Typed language”

A

Go enforces static typing meaning variable types are known before the code runs. That means your editor and the compiler can display type errors before the code is ever run, making development easier and faster.

Contrast this with most dynamically typed languages like JavaScript and Python… Dynamic typing often leads to subtle bugs that are hard to detect. The code must be run to catch syntax and type errors. (sometimes in production if you’re unlucky 😨)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Go - Small memory footprint?

A

Go programs are fairly lightweight. Each program includes a small amount of extra code that’s included in the executable binary called the Go Runtime. One of the purposes of the Go runtime is to clean up unused memory at runtime. It includes a garbage collector that automatically frees up memory that’s no longer in use.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Constants declaration in go

A

Constants are declared with the const keyword. They can’t use the := short declaration syntax.
Example:
const pi = 3.14159

Constants can be primitive types like strings, integers, booleans and floats. They cannot be more complex types like slices, maps and structs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Top 5 Verbs for Sprintf

A

%v
It takes pretty much any variable type and formats it in the default style for that type. Unfortunately, since it is not as precise about what it does, it’s used less in production code. However, it is great for early-stage development, experimenting, and debugging.

%s
Simply a string. This verb doesn’t interpret the string that’s passed in and so it shows up as is.

%q
This verb formats values (i.e., arguments) with quotes. This is handy when you need quoted and quote-escaped values.

%d
%d formats a regular old base-10 integer number.

%t
Presumably ‘t’ here stands for true as %t formats a boolean value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is “func sub(x int, y int) int” is known as

A

the “function signature”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

go runtime use

A

Its part of created binary from your code. But what does it do,
- memory management
- concurrency
- built in data structures

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

waitgroups

A

Golang Waitgroup allows you to block a specific code block to allow a set of goroutines to complete execution. An example would be to block the main function until the goroutines are completed and then unblocks the group.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

empty interface in go (interface{} aka any)

A

The empty interface in Go allows for the creation of heterogeneous collections, enabling storage of different data types in a single collection. It is widely used in the fmt package, allowing functions like fmt.Println to accept any input.

17
Q

struct field tags

A

For each specific format like json, sql, mysql, we could specify what is the display name.
when we add tag for json, it displays that tag when we print json.

18
Q

Array, Slice, and Map

A

//array syntax or example
var myArr [5]string
myArr := […]int{10, 39, 34}

//slice syntax or example
mySlice := make ([]string, len, cap)
mySlice := make ([]int, 5,5)

//map syntax or example
mapName := map[string]int{“a”:1}
myMap := make(map[string]int, 5<capacity>)</capacity>

19
Q

array

A
  • collection of similar data elements stored in contiguous memory locations.
  • its homogeneous in nature.
  • fixed length - means its not flexible.
  • length (property) - no of elements in array
  • capacity (property) - no of elements that it can contain
  • in array, both length and capacity will be same

Syntax:
Option 1: var keyword:

var*array_name =*[*length*]*datatype*{*values*}// here length is defined

or

var*array_name =*[...]*datatype*{*values*}**// here length is inferred

Option 2: := keyword:

array_name := [length]datatype{values} // here length is defined

or

*array_name*:= [...]*datatype*{*values*}**// here length is inferred

Example:

```go
var arr1 = [3]int{1,2,3}
arr2 := [5]int{4,5,6,7,8}

~~~

20
Q

slices

A
  • Slice is a continuous segment of underlying array
  • Variable typed (elements can be added or removed)
  • flexible
  • Slice has 3 main components - pointers, length and capacity.
  • len - length of a slice
  • cap- total size(capacity) of a slice. If we are adding a number to a slice continuously, it allocates in 2 power n sequency. Below is an example.
  • Size needs to be skipped in slice.

initialization:
slice := make ([]int, 5,5)

21
Q

maps

A
  • un ordered pair of key values
  • implemented by hash tables
  • efficient in add, get, and delete operations

Syntax and example:
- var myMap map[string]int
- nil map does not contain any keys and when a value is added it it, we get run time error.
- hence do it with initialization (maybe with make)
- mapName := map[string]int{”abc”:1,”bcd”:2}
- Syntax with Make: mapName := make(map[string]int, 5<initialize capacity>)

Additional Notes:
- len can be used to know no of items in map
- delete key value pairs with this - delete(<myMap>, <key>)
- update with - myMap[<newKey>]=<value>
- Iterate with for loop - for key, value := range myMap { ... }
- truncate (clearing all elements in map) -
—> slow method: deleting keys on by one as we iterate via for loop

```go
for key, value := range myMap{
delete (codes, key)
}
~~~

—> fast method - reinitialize

myMap = make(map[string]string)

22
Q

Pointer

A

& - address of variable
* - dereferencing value

eg: var ptr_i *int

Additional info:
- pointers with slice and maps - as these are reference types, know better when you use it.
- pointers with Slice make sense when you wanted to modify capacity or length of it, Otherwise not.
- Best Practices:
- Avoid unnecessary pointers. If its for a small size variable, it’s better to use just variable.
- check for nil pointers, as that can lead to runtime errors.
- When used correctly, it can optimize performance of your app.

23
Q

dereferencing a pointer

A

Dereferencing a pointer gives us access to the value the pointer points to.

24
Q

passing by value

A

parameter is copied into another location in memory.
means, modifying data inside function will not affect original data.
all basic types like int, float, string, bool, array are passed by value.
it’s how we generally pass value, except for slice and maps.

25
Q

passing by reference

A

call by reference/pointer means, address of variable is passed to function as a parameter. Means changes to it will modify the original value.

By default, maps and slices are passed by reference.

26
Q

structs

A
  • user defined data type
  • it groups together data elements
  • provides way to reference series of grouped values through a single variable
  • used when it make sense to group or associate two or more data variable

`
type <structName> struct{
//list of fields
}</structName>

//initilize
var <varName> <tructName>
`</tructName></varName>

`
type <structName> struct{
//list of fields
}</structName>

//initilize
//method 1
var <varName> <tructName></tructName></varName>

//method 2

<variableName> := new(<structName>)

//method 3
<variableName> := <structName> {
<fieldName> : <value>,
<fieldName> : <value>,
}
`

- accessing fields of struct with <variableName>.<fieldName> example: s.xName
</fieldName></variableName></value></fieldName></value></fieldName></structName></variableName></structName></variableName>

27
Q

go-routines

A
  • light weight threads, that has separate independent execution
  • can execute concurrently
  • syntax: go funcName()
  • main function in main package is the main go routine.
  • all go-routine exits, if main go-routine exits.
  • no parent child concept in go-routine, instead runs independently.