[Go](EN) Go language struct and method basic usage

Post about basic usage of struct and method in Go language


Environment and Prerequisite

  • Go(1.15.8)
  • Experience with other programming languages


Struct and Method

Struct in Go

  • Go language supports its own way of OOP. There is no class in Go. Also no class so no inheritance.
  • So it use struct and method.
  • Briefly write about struct and method in below.


Struct Example

  • There are four ways like below example.
  • We can use keyword new or we can make constructor function.
package main

import (
    "fmt"
)

// define struct
type Rectangle struct {
    width int
    height int
}

// define constructor
func NewRectangle(width int, height int) *Rectangle{
    return &Rectangle{width, height}
}

func main() {

    // create instances
    var rec1 = Rectangle{}
    rec1.width = 2
    rec1.height = 3

    rec2 := Rectangle{4, 5}

    var rec3 = new(Rectangle)
    rec3.width = 6
    rec3.height = 7

    var rec4 = NewRectangle(8, 9)

    // check instances
    fmt.Println(rec1.width, rec1.height)
    fmt.Println(rec2.width, rec2.height)
    fmt.Println(rec3.width, rec3.height)
    fmt.Println(rec4.width, rec4.height)
}
2 3
4 5
6 7
8 9


Method Example

  • By using receiver, we can define method for specific class.
  • There are value receiver and pointer receiver.
  • In below example, (r Rectangle) and (r *Rectangle) are receivers.
package main

import (
    "fmt"
)

// define struct
type Rectangle struct {
    width int
    height int
}

// define constructor
func NewRectangle(width int, height int) *Rectangle{
    return &Rectangle{width, height}
}

// define methods
func (r Rectangle) area() int{
    return r.width * r.height
}

// pointer receiver
func (r *Rectangle) setWidth(width int){
    r.width = width
}

// value receiver
func (r Rectangle) setHeight(height int){
    r.height = height
}

func main() {

    // create instances
    var rec = NewRectangle(8, 9)

    // check instances
    fmt.Println(rec.width, rec.height)
    fmt.Println()

    // check methods
    fmt.Println(rec.area())
    fmt.Println()

    rec.setWidth(10)
    // rec.height would not be changed because its method's receiver is value receiver
    rec.setHeight(10)
    fmt.Println(rec.width, rec.height)
}
8 9

72

10 9


Reference