Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Method Chaining in Go (Golang)

Posted on June 20, 2023June 20, 2023 by admin

For method chaining to be possible, the methods in the chain should return the receiver. Returning the receiver for the last method in the chain is optional.

Let’s see an example of method chaining.

package main
import "fmt"
type employee struct {
name string
age int
salary int
}
func (e employee) printName() employee {
fmt.Printf("Name: %s\n", e.name)
return e
}
func (e employee) printAge() employee {
fmt.Printf("Age: %d\n", e.age)
return e
}
func (e employee) printSalary() {
fmt.Printf("Salary: %d\n", e.salary)
}
func main() {
emp := employee{name: "Sam", age: 31, salary: 2000}
emp.printName().printAge().printSalary()
}

Output

Name: Sam
Age: 31
Salary: 2000
  • go
  • golang
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP