Online Golang Compiler - Instantly Run and Test Go Code

Write, compile, and run Golang code right in your browser with our free online Go compiler. It's perfect for learning, quick testing, and interview prep — no setup or installation needed.

💡 Go Basics Guide for Beginners

1. Declaring Variables and Constants

Use var or := to declare variables. Use const for constants.

package main

var x int = 10
const Pi = 3.14

func main() {
    name := "Alice"
    isActive := true
    println(x, Pi, name, isActive)
}

2. Conditionals (if / switch)

Go supports if-else and switch statements with clean syntax.

x := 2
if x == 1 {
    println("One")
} else if x == 2 {
    println("Two")
} else {
    println("Other")
}

switch x {
case 1:
    println("One")
case 2:
    println("Two")
default:
    println("Other")
}

3. Loops

Go uses only the for loop, but it can act like a while loop.

for i := 0; i < 3; i++ {
    println(i)
}

n := 3
for n > 0 {
    println(n)
    n--
}

4. Arrays

Arrays have fixed size. Use slices for dynamic lists.

var nums = [3]int{10, 20, 30}
println(nums[1])

5. Slice Manipulation

Use slices and the built-in append, len, copy, and slicing syntax.

fruits := []string{"apple", "banana"}
fruits = append(fruits, "cherry")
fruits = fruits[1:]  // slice
println(len(fruits))

for _, fruit := range fruits {
    println(fruit)
}

6. Console Input/Output

Use fmt.Print, fmt.Scan, and fmt.Println.

import "fmt"

var name string
fmt.Print("Enter your name: ")
fmt.Scan(&name)
fmt.Println("Hello", name)

7. Functions

Functions are declared with func and can return multiple values.

func greet(name string) string {
    return "Hello, " + name
}

message := greet("Alice")
println(message)

8. Maps

Maps are key-value stores. Declare with make().

ages := map[string]int{"Alice": 30}
ages["Bob"] = 25
println(ages["Alice"])

9. Error Handling

Go uses multiple return values for errors instead of exceptions.

import "errors"

func fail() error {
    return errors.New("something went wrong")
}

err := fail()
if err != nil {
    println(err.Error())
}

10. File I/O

Use os and io/ioutil packages to read/write files.

import (
  "fmt"
  "os"
  "io/ioutil"
)

ioutil.WriteFile("file.txt", []byte("Hello File"), 0644)

data, _ := ioutil.ReadFile("file.txt")
fmt.Println(string(data))

11. String Manipulation

Use the strings package for string operations.

import "strings"

text := "  Hello World  "
println(strings.TrimSpace(text))
println(strings.ToUpper(text))
println(strings.ReplaceAll(text, "Hello", "Hi"))

words := strings.Split(text, " ")
fmt.Println(words)

12. Structs & Objects

Use structs to define custom types with methods.

type Person struct {
  Name string
}

func (p Person) Greet() string {
  return "Hi, I'm " + p.Name
}

p := Person{Name: "Alice"}
println(p.Greet())

13. References (Pointers)

Go supports pointers using * and &.

x := 10
ptr := &x
*ptr = 20
println(x) // 20