Functions cascades within struck

I have a doubt and i don’t know how look it for the solution.

If you work with gorm sometime you write a query like this:

db.Select("AVG(age) as avgage").Group("name").Having("AVG(age) > (?)", subQuery).Find(&results)

With that in mind i wish to create a structure like this

package main

type Foo struct{

        ID int
        name string

}

func (f *Foo) GetName(){

        return f.name

}

func (f *Foo) GetID(){
        return f.ID
}

func (f *Foo) ToString(num int){

        id,_:=strconv.Itoa(num)
        return id
}

f:=&Foo{
        ID:1
}

f.GetID().ToString()

What I expect is get the ID value as string

So my questions are:

  1. How it is called? Is a function cascade?

  2. Is this possible?

Feel free to change the code example if you think this is possible.
Thank you

  1. How it is called? Is a function cascade?

It is called method chaining

  1. Is this possible?

It is possible, but not with your example. In gorm the chaining happens since every method in chain returns the type *DB. Which has next method in chain.

Here you need to use something like:

f.ToString(f.GetID())

Sometimes, you can encounter custom types, which allows you to expand the base type with new methods e.g.:

package main

import (
	"fmt"
	"strconv"
)

type ID int

func (id ID) String() string {
	return strconv.Itoa(int(id))
}

type Foo struct {
	id   ID
	name string
}

func (f *Foo) GetName() string {
	return f.name
}

func (f *Foo) GetID() ID {
	return f.id
}

func main() {
	f := &Foo{id: ID(4), name: "name"}
	fmt.Println(f.GetID().String()) // Prints 4.
}

Your answer was really helpful. Thank you lemarkar

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.