Go: Declaring and using objects

Go (or Golang) doesn’t have the concept of classes. The class equivalent in Go loos like this:

  // Make a Car class equivalent
  type Car struct {
    // object properties go here
    doors int

  }

  // Get the number of doors 
  func (car *Car) Doors() int {
    return car.doors
  }

  // Set the number of doors in a car
  func (car *Car) SetDoors(doors int) {
    car.doors = doors
  }

The above declaration can now be used as an object like so:

  import fmt

  func main() {
    lamborgini := new(Car)
    lamborgini.setDoors(2)

    fmt.Println("This lamborgini has: " + lamborgini.Doors()  + " Doors")    
  }


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *