DEV Community

Cover image for Go methods
bluepaperbirds
bluepaperbirds

Posted on

1 1

Go methods

Go does not have classes or object orientated programming in the traditional sense. But you can define methods on types.

In Go, a method is a function with a special receiver argument. For example, we define two methods like that (getX and getY):

package main

import (
    "fmt"
)

type Coordinate struct {
    X, Y float64
}

func (v Coordinate) getX() float64 {
    return v.X
}

func (v Coordinate) getY() float64 {
    return v.Y
}

func main() {
    v := Coordinate{3, 4}
    fmt.Println(v.getX())
    fmt.Println(v.getY())
}

This outputs the x and y values of the struct.

3
4

Program exited.

So on a programming level with Go, you might not miss OOP as structs work just fine and you can apply methods.

A method can do more than just return a value. In the example below, the method Abs has a receiver of type Vertex named v.

package main

import (
    "fmt"
    "math"
)

type Vertex struct {
    X, Y float64
}

func (v Vertex) Abs() float64 {
    return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func main() {
    v := Vertex{3, 4}
    fmt.Println(v.Abs())
}

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay