Go chapters

Chapter 16 of 17

Go Syntax Cheatsheet

Try this in our Go Compiler →

Everything in one place

Use this chapter as a quick reference once you've worked through the rest of the course. It collects every core construct of Go into runnable, copy-pasteable snippets you can scan whenever you forget the exact syntax.

Hello world & variables

```go
package main

import "fmt"

func main() { fmt.Println("Hello, World!") }

age := 25 name := "Aman" isStudent := true fmt.Println(name, age, isStudent) ```

Data types & operators

```go
var n int = 42
var f float64 = 3.14
var s string = "hello"
var b bool = true
var arr [3]int = [3]int{1, 2, 3}

a, b := 10, 3 fmt.Println(a+b, a-b, a*b, a/b, a%b) fmt.Println(a > b && b < 5) ```

Conditionals & loops

```go
score := 72
if score >= 90 {
    fmt.Println("A")
} else if score >= 60 {
    fmt.Println("Pass")
} else {
    fmt.Println("Fail")
}

for i := 0; i < 5; i++ { fmt.Println(i) }

n := 0 for n < 3 { n++ } ```

Functions & arrays

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

func main() { fmt.Println(add(2, 3)) }

nums := []int{10, 20, 30} nums = append(nums, 40) for i, n := range nums { fmt.Println(i, n) } ```

Strings & objects

```go
name := "PlayLearn"
fmt.Println(len(name))
fmt.Println(strings.ToUpper(name))
greet := fmt.Sprintf("Hello, %s!", name)

type User struct { Name string Age int }

func (u User) Greet() string { return "Hi " + u.Name }

u := User{"Aman", 20} fmt.Println(u.Greet()) ```

Errors, modules & I/O

```go
f, err := os.Open("missing.txt")
if err != nil {
    fmt.Println("open failed:", err)
    return
}
defer f.Close()

// math/math.go package math func Add(a, b int) int { return a + b }

// main.go import "myapp/math" fmt.Println(math.Add(2, 3))

var name string fmt.Print("Your name? ") fmt.Scanln(&name) fmt.Println("Hello,", name) ```

How to use this page

Bookmark it. When you start a new project, open this cheatsheet alongside your editor and use it as a syntax lookup. Once a construct becomes second nature you'll stop needing the reference for it — and that's exactly when you know you've mastered that part of Go.

Try it yourself

Go Compiler
Output
Code runs on the Play with Coding execution engine — your code is saved locally for next time.