Structs
Go isn't quite an OOP language, but the closest thing to OOP in go is structs which we will cover in this section.
The basic Idea
// declare the type of the struct
type Book struct {
title string
year_published int // set the fields in the struct
author string // the fields can be of different types
price float64
}
Usage
package main
import "fmt"
func new_book(title string, year_published int, author string, price float64) *Book {
book := Book{title: title}
book.author = author
book.year_published = year_published
book.price = price
return &book
}
func main() {
// create a new struct
book := Book{title: "Blue Nights", year_published: 2017, author: "Joan Didion", price: 29.99}
fmt.Println(book)
// access the fields of the struct
fmt.Println(book.title)
fmt.Println(book.year_published)
fmt.Println(book.author)
fmt.Println(book.price)
// change the value of a field
book.price = 19.99
fmt.Println(book.price)
// create a new struct with the new keyword
book2 := new(Book)
book2.title = "Life of Pi"
book2.year_published = 2001
book2.author = "Yann Martel"
book2.price = 9.99
fmt.Println(book2)
// create a new struct with a function
// this is somewhat similar to a constructor in other languages
// however, it is considered more idiomatic to do this in Go
book3 := new_book("Utilitarianism", 1861, "John Stuart Mill", 9.99)
fmt.Println(book3)
}
Struct methods
Last updated