👊
Go tutorial for Pythoner
  • Introduction
  • Install and Run Go
  • The structure of Go
    • First time you meet him
    • Functions
    • Return multiple results
    • Logic Control
    • Break loop and enumerate
    • List (Array or Slice)
    • Dict (Map)
    • Struct
    • Class (Methods)
    • Packages
  • Features of Go
  • Go modules
  • Web Server
    • Serving static files
    • A simple webserver
  • Go for Android
  • Where to go next
Powered by GitBook
On this page
  • Python Version
  • Golang Version

Was this helpful?

  1. The structure of Go

Class (Methods)

I can't believe when sentdex tell me that Golang doesn't have class methods.

But soon I know what's the big idea under the mystery.

Python Version

class box():
    def __init__(self, length, width, hight):
        self.length = length
        self.width = width
        self.hight = hight

    def get_volume(self):
        return self.length * self.width * self.hight
    
    def change_length(self):
        self.length = length // 2

box_a = box(3, 2, 1)
box_b = box(4, 2, 2)
print('The volume of box_a is', box_a.get_volume())
print('The volume of box_b is', box_b.get_volume())

Golang Version

package main

import "fmt"


type box struct {
    length int16
    width int16
    hight int16
}

func (b *box) get_volume() int16 {
    return b.length * b.width * b.hight
}

func (b *box) change_length() {
    b.length = b.length / 2
}

func main(){
    box_a := box{length: 3, width: 2, hight: 1}
    box_b := box{length: 4, width: 2, hight: 2}

    fmt.Println("The volume of box_a is", box_a.get_volume())
    fmt.Println("The volume of box_b is", box_b.get_volume())
}

This is the basic way for class method.

You can also pass pointer to class function:

package main

import "fmt"

type box struct {
    length int16
    width int16
    hight int16
}

func (b *box) get_volume() int16 {
    return b.length * b.width * b.hight
}

func main(){
    box_a := box{length: 3, width: 2, hight: 1}

    fmt.Println("The volume of box_a is", box_a.get_volume())
}
PreviousStructNextPackages

Last updated 3 years ago

Was this helpful?