# Golang intro

# **The Compilation Process**

Computers need machine code, they don't understand English or even Go. We need to convert our high-level (Go) code into machine language, which is really just a set of instructions that some specific hardware can understand. In your case, your CPU.

The Go compiler's job is to take Go code and produce machine code, an `.exe` file on Windows or a standard executable on Mac/Linux.

![](https://storage.googleapis.com/qvault-webapp-dynamic-assets/course_assets/rfR5MNc-1280x490.png align="left")

## **Go Program Structure**

We'll go over this all later in more detail, but to sate your curiosity:

1. `package main` 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.
    
2. `import "fmt"` imports the [`fmt` (formatting) package](https://pkg.go.dev/fmt) from the [standard library](https://pkg.go.dev/std). It allows us to use `fmt.Println` to print to the console.
    
3. `func main()` defines the `main` function, the entry point for a Go program.
    

## **Kinds of bugs**

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

1. **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.
    
2. **Runtime errors.** Occur when a program is running. These are generally worse because they can cause your program to crash or behave unexpectedly.
    

## 🗨️ 1. Go Comments

### ➤ Single-line comment

```go
// This is a single-line comment
```

### ➤ Multi-line comment

```go
/*
This is a
multi-line comment
*/
```

## ✅ 2. Data Types in Go 🔠

| Category | Type | Description |
| --- | --- | --- |
| Integer | `int`, `int8`, `int16`, `int32`, `int64` | Signed integers |
| Unsigned int | `uint`, `uint8`, `uint16`, `uint32`, `uint64`, `uintptr` | Unsigned integers |
| Float | `float32`, `float64` | Decimal numbers |
| Complex | `complex64`, `complex128` | Complex numbers |
| Boolean | `bool` | true / false |
| String | `string` | UTF-8 text |
| Byte | `byte` | Alias for `uint8` |
| Rune | `rune` | Alias for `int32`, represents a Unicode character |

## **Common ones :**

* * `bool`
        
        * `string`
            
        * `int`
            
        * `uint`
            
        * `byte`
            
        * `rune`
            
        * `float64`
            
        * `complex128`
            

## [✅](https://pkg.go.dev/fmt#hdr-Printing) 3. **Variable Declaration in Go**

### ➤ Using `var` keyword

```go
var a int = 10
var b string      // Default zero value is ""
var c = 20        // Type inferred as int
```

### ➤ Short-hand declaration (only inside functions)

```go
x := 5
name := "Raj"
```

### ➤ Multiple variable declaration

```go
var x, y int = 1, 2
var a, b = 10, "hello"
a, b := 2.3, "is average"
```

### ➤ Constants

```go
const pi = 3.14
const name string = "Raj"
```

Constants are declared with the `const` keyword. They can't use the `:=` short declaration syntax.

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

However, constants *can be computed* as long as the computation can happen at *compile time.*

Eg, this is valid:

```go
const firstName = "Lane"
const lastName = "Wagner"
const fullName = firstName + " " + lastName
```

That said, you *cannot* declare a constant that can only be computed at run-time like you can in JavaScript. This breaks:

```go
// the current time can only be known when the program is running
const currentTime = time.Now()
```

## [✅](https://pkg.go.dev/fmt#hdr-Printing) 4. **More on strings**

## ➤ Type Conversion :

Type conversion is simple in go:

```go
temperatureFloat := 88.26
temperatureInt := int(temperatureFloat)
```

## ➤ Concatenating Strings :

Two strings can be concatenated with [t](https://en.wikipedia.org/wiki/Concatenation)he `+` operator.

But the compiler will not allow you to concatenate a `string` variable with an `int` or a `float64`.

## ➤ **Formatting Strings:**

* fmt.Printf - Prints a formatted string to standard out.
    
* fmt.Sprintf() - Returns the formatted string
    

### **Default common representation:**

```go
s := fmt.Sprintf("I am %v years old", 10)  // I am 10 years old
s := fmt.Sprintf("I am %v years old", "too many") // I am too many years old
```

### **Data type specific representation:**

```go
s := fmt.Sprintf("I am %s years old", "way too many")   // I am way too many years old
s := fmt.Sprintf("I am %d years old", 10)               // I am 10 years old
s := fmt.Sprintf("I am %f years old", 10.523)           // I am 10.523000 years old
s := fmt.Sprintf("I am %.2f years old", 10.523)         // I am 10.52 years old
```

## ➤ Runes and string encoding :

In many programming languages (cough, C, cough), a "character" is a single byte. Using [ASCII](https://www.asciitable.com/) encoding, the standard for the C programming language, we can represent 128 characters with 7 bits. This is enough for the English alphabet, numbers, and some special characters.

In Go, strings are just sequences of bytes: they can hold arbitrary data. However, Go also has a special type, [`rune`](https://go.dev/blog/strings), which is an alias for `int32`. This means that a `rune` is a 32-bit integer, which is large enough to hold any [Unicode](https://home.unicode.org/) code point.

When you're working with strings, you need to be aware of the encoding (bytes -&gt; representation). Go uses [UTF-8](https://en.wikipedia.org/wiki/UTF-8) encoding, which is a variable-length encoding.

SO There are 2 main takeaways:

1. When you need to work with individual characters in a string, you should use the `rune` type. It breaks strings up into their individual characters, which can be more than one byte long.
    
2. We can include a wide variety of Unicode characters in our strings, such as emojis and Chinese characters, and Go will handle them just fine.
    

### **Sample code demonstration:**

```go
s := 5

package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {
	const name = "r"
	const face = "🐻"
	fmt.Printf("length by len(var) for name, face: %d %d\n", len(name), len(face))
	fmt.Printf("length by rune() for name, face: %d %d\n", utf8.RuneCountInString(name), utf8.RuneCountInString(face))
}

// 1 4
// 1 1
```
