how to attach functions to structs?

In Go this is called “defining a method on a type”. It works like this:

package main

import (

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}

This example is taken straight from the Tour of Go which I highly recommend any newcomer should take.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top