Defining Structs
A struct groups several related pieces of data into one new type. For example, instead of keeping a book's title, author, and page count in three separate variables, you create a Buku (book) type:
type Buku struct {
Judul string
Penulis string
Halaman int
Tersedia bool
}
Each line inside the struct is called a field, made up of a name and a type. Here that's the title, author, number of pages, and whether the book is available.
Creating a struct value
// dengan nama field (disarankan, urutan bebas)
b := Buku{
Judul: "Hujan di Kota Tua",
Penulis: "Ratna",
Halaman: 240,
}
// tanpa nama field: semua field wajib diisi, sesuai urutan
b2 := Buku{"Gunung dan Laut", "Bayu", 180, true}
You can create it with field names (recommended, any order), or without field names — in which case every field must be filled in, in order. The field names style is safer: your code stays correct even if the order of the fields in the struct changes. Also note the comma after the last field when the closing brace is on the next line.
Reading and changing fields
Use a dot (.):
fmt.Println(b.Judul) // Hujan di Kota Tua
b.Tersedia = true
A struct's zero value
Any field you don't set automatically holds the zero value for its type. Even a struct declared with no value at all is ready to use:
var kosong Buku
fmt.Println(kosong.Halaman) // 0
fmt.Println(kosong.Judul == "") // true
fmt.Printf("%+v\n", kosong)
// {Judul: Penulis: Halaman:0 Tersedia:false}
The %+v verb prints a struct along with its field names — really useful when debugging.
Task
The library system already has a Buku type. Complete two functions:
-
bukuBaru(judul, penulis string, halaman int) Buku— return aBukuwith the fields set from the arguments andTersediaset totrue(a new book can always be borrowed). -
deskripsiBuku(b Buku) string— return text in this format:<Judul> oleh <Penulis> (<Halaman> halaman)(In English, that reads
<Title> by <Author> (<Pages> pages).)Example:
Hujan di Kota Tua oleh Ratna (240 halaman)