Start learning free

LESSON 279 OF 671 · FUNCTIONS & CLASSES

Defining a Class in Go

Lesson

TL ; DR:

  • A class is a blueprint for creating objects. It groups together related data and behavior under a single name.


  • In Go, you define a struct type with the type keyword, followed by the type name, the struct keyword, and a pair of curly braces:

    type Dog struct {
    }
    

    The body of the struct can be empty — that's still a valid type. We'll add data and behavior to it in the next lessons.



Full lesson:

So far, you've worked with built-in types like int, string, and arrays. But what if you want to model something the language doesn't have a type for — like a Dog, a BankAccount, or a Game?

That's what classes are for. A class lets you define your own type by listing what data it holds and what actions it can perform.


Why classes?

Imagine you're writing a program about dogs. Each dog has a name, an age, and can bark. Without classes, you'd have to track each dog's name in one variable, age in another, and write a separate bark() function for each. That gets messy fast.

With a class, you bundle all of that into one neat package called Dog:

type Dog struct {
    // We'll add fields and methods in upcoming lessons.
}

The syntax

Defining an empty struct type in Go looks like this:

type TypeName struct {
}

Three things to notice:

  • The keyword type tells Go you're defining a new type, and struct specifies that it's a struct.

  • TypeName is the name you choose. By convention, Go type names use PascalCase — capitalized words with no underscores: Dog, BankAccount, HighScore.

  • The curly braces { } hold the body of the struct. Go does not need a semicolon after the closing brace.


No classes: struct + receiver methods:

Go has no class keyword. You define a struct for the data, then attach behavior with methods that take a receiver — the value in parentheses before the method name. You call it with dot syntax, just like a method on an object.

type Dog struct {
}

func (d Dog) bark() {
    fmt.Println("Woof!")
}

d := Dog{}
d.bark() // prints Woof!

You'll see this func (d Dog) ... receiver style throughout the coding tutorials — it's how Go gives a type its behavior without classes.


Your task

Define an empty struct type called Dog. The pre-filled code in mainFunction will create an instance of your type and print a confirmation message. If you define the type correctly, the program will compile and print:

Defined the Dog class!
STEP 1 OF 1
    Ctrl + Enter to check