← Back to course: Go from scratch

Structs and methods

Video coming soon

Basic types hold a single piece of data, but real-world things have several properties: a user has a name, email and age; a product has a name, price and stock. To group related data Go uses the struct. Go has no classes or inheritance like Java or Python; instead it combines structs, methods and interfaces, which you will see today and in the next lessons. This combination is simpler and, with practice, turns out to be very flexible.

Defining and creating structs

It is defined with type Name struct { fields }. Each field has a name and a type. To create a value you use a literal with field names, which is the recommended form because it does not depend on order and is readable. Fields you omit get their zero value. Each field is accessed with a dot. A field whose name starts with an uppercase letter is exported, that is, visible from other packages; lowercase means private to the package. Two structs with the same comparable fields can be compared with ==, and assigning a struct copies it entirely.

go
package main

import "fmt"

type Address struct {
	City    string
	Country string
}

type User struct {
	Name    string
	Email   string
	Age     int
	Address Address // nested struct
}

func main() {
	u := User{
		Name:  "Ana",
		Email: "ana@example.com",
		Age:   30,
		Address: Address{City: "Madrid", Country: "Spain"},
	}
	fmt.Println(u.Name, u.Address.City)

	v := u // full copy
	v.Name = "Bea"
	fmt.Println(u.Name, v.Name) // Ana Bea
	fmt.Printf("%+v\n", u)     // prints field names too

	var empty User
	fmt.Println(empty.Age, empty.Name == "") // 0 true
}

Methods

A method is a function associated with a type. It is declared like a normal function, but with a receiver in parentheses before the name: func (r Rectangle) Area() float64. Inside the method, the receiver is used like any other variable. Methods are called with a dot on a value: rect.Area(). You can define methods on any type of your own, not just structs: for example on a type Celsius float64. All methods of a type must live in the same package as the type.

go
package main

import (
	"fmt"
	"math"
)

type Rectangle struct {
	Width, Height float64
}

func (r Rectangle) Area() float64 {
	return r.Width * r.Height
}

func (r Rectangle) Perimeter() float64 {
	return 2 * (r.Width + r.Height)
}

type Circle struct {
	Radius float64
}

func (c Circle) Area() float64 {
	return math.Pi * c.Radius * c.Radius
}

type Celsius float64

func (c Celsius) ToFahrenheit() float64 {
	return float64(c)*9/5 + 32
}

func main() {
	r := Rectangle{Width: 3, Height: 4}
	fmt.Println(r.Area(), r.Perimeter()) // 12 14
	fmt.Printf("%.2f\n", Circle{Radius: 2}.Area()) // 12.57
	fmt.Println(Celsius(100).ToFahrenheit()) // 212
}

Constructors and composition

Go has no special constructors. By convention you write a function called NewSomething that validates the data and returns the value ready to use, together with an error if something is invalid. Instead of inheritance, Go offers composition: you can embed a struct inside another without giving it a field name, and the inner one's fields and methods become directly available in the outer one. This is called struct embedding. It is not inheritance, because there is no type hierarchy, but it allows reusing behavior in a simple way.

go
package main

import (
	"errors"
	"fmt"
)

type Person struct {
	Name string
}

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

type Employee struct {
	Person // embedded: Name and Greet are promoted
	Salary float64
}

func NewEmployee(name string, salary float64) (Employee, error) {
	if name == "" {
		return Employee{}, errors.New("name is required")
	}
	return Employee{Person: Person{Name: name}, Salary: salary}, nil
}

func main() {
	e, err := NewEmployee("Luis", 2500)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(e.Name, e.Greet(), e.Salary)
}
  • type T struct { ... } groups related fields.
  • Use named literals: User{Name: "Ana"}.
  • Leading uppercase = exported; lowercase = private.
  • func (r T) Method() attaches behavior to the type.
  • Composition with embedding instead of inheritance.

✎ My notes

Saved only in this browser. Sign in to keep it in your account.0/5000 characters

← PreviousNext →