# Golang for TypeScript devs

# Variables & Types

**TypeScript:**

```typescript
let name: string = "john";
const age: number = 25;
let active: boolean = true;
let items: string[] = ["a", "b"];
```

**Go:**

```go
var name string = "john"  // or: name := "john"
const age int = 25
active := true
items := []string{"a", "b"}
```

# Functions

**TypeScript:**

```typescript
function add(a: number, b: number): number {
  return a + b;
}

const multiply = (a: number, b: number): number => a * b;
```

**Go:**

```go
func add(a int, b int) int {
    return a + b
}

// Go doesn't have arrow functions, just regular functions
func multiply(a, b int) int {
    return a * b
}
```

# Error Handling

**TypeScript:**

```typescript
try {
  const result = riskyFunction();
} catch (error) {
  console.log(error);
}
```

**Go:**

```go
result, err := riskyFunction()
if err != nil {
    log.Println(err)
}
```

# HTTP Requests

**TypeScript:**

```typescript
const response = await fetch("https://api.example.com/data");
const data = await response.json();
```

**Go:**

```go
resp, err := http.Get("https://api.example.com/data")
if err != nil {
    return err
}
defer resp.Body.Close()

var data interface{}
json.NewDecoder(resp.Body).Decode(&data)
```

# Loops

**TypeScript:**

```typescript
// For loop
for (let i = 0; i < 10; i++) {}

// Array iteration
items.forEach((item) => console.log(item));

// For...of
for (const item of items) {
}
```

**Go:**

```go
// For loop
for i := 0; i < 10; i++ {}

// Slice iteration
for _, item := range items {
    fmt.Println(item)
}

// With index
for i, item := range items {
    fmt.Printf("%d: %s\n", i, item)
}
```

# Objects/Structs

**TypeScript:**

```typescript
interface User {
  name: string;
  age: number;
}

const user: User = { name: "john", age: 25 };
```

**Go:**

```go
type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

user := User{Name: "john", Age: 25}
```

# JSON

**TypeScript:**

```typescript
const jsonStr = JSON.stringify(obj);
const obj = JSON.parse(jsonStr);
```

**Go:**

```go
jsonBytes, _ := json.Marshal(obj)
jsonStr := string(jsonBytes)

var obj MyStruct
json.Unmarshal([]byte(jsonStr), &obj)
```

# Conditionals

**TypeScript:**

```typescript
if (condition) {
  // do something
} else if (other) {
  // do other
} else {
  // default
}

const result = condition ? "yes" : "no";
```

**Go:**

```go
if condition {
    // do something
} else if other {
    // do other
} else {
    // default
}

// No ternary operator, use if/else
var result string
if condition {
    result = "yes"
} else {
    result = "no"
}
```

# Arrays/Slices

**TypeScript:**

```typescript
const items = [1, 2, 3];
items.push(4);
const filtered = items.filter((x) => x > 2);
const mapped = items.map((x) => x * 2);
```

**Go:**

```go
items := []int{1, 2, 3}
items = append(items, 4)

// No built-in filter/map, write loops
var filtered []int
for _, x := range items {
    if x > 2 {
        filtered = append(filtered, x)
    }
}
```

# String Operations

**TypeScript:**

```typescript
const text = `Hello ${name}`;
const parts = text.split(" ");
const joined = parts.join("-");
```

**Go:**

```go
text := fmt.Sprintf("Hello %s", name)
parts := strings.Split(text, " ")
joined := strings.Join(parts, "-")
```

# Async/Promises → Goroutines

**TypeScript:**

```typescript
async function fetchData() {
  const result = await someAsyncFunction();
  return result;
}

Promise.all([fetch1(), fetch2()]);
```

**Go:**

```go
func fetchData() (string, error) {
    // Go doesn't have async/await
    // Use goroutines for concurrency
    return someFunction()
}

// Concurrent execution
ch := make(chan string, 2)
go func() { ch <- fetch1() }()
go func() { ch <- fetch2() }()

result1, result2 := <-ch, <-ch
```

# Key Differences to Remember

* **No classes** → Use structs and methods
    
* **No null/undefined** → Use zero values and pointers
    
* **Explicit error handling** → No try/catch, check `err != nil`
    
* **No generics** (until Go 1.18+) → Interface{} or code generation
    
* **Package system** → Import paths, not node\_modules
    
* **Compiled** → `go build` creates binary
    
* **Garbage collected** but more explicit about memory
    
* **Goroutines** instead of async/await
