Go course

StructsDefining Structs

Go

Display

Theme

Structs · Test exercise

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:

  1. bukuBaru(judul, penulis string, halaman int) Buku — return a Buku with the fields set from the arguments and Tersedia set to true (a new book can always be borrowed).

  2. 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)

main.go
package main

import "fmt"

type Buku struct {
	Judul    string
	Penulis  string
	Halaman  int
	Tersedia bool
}

func bukuBaru(judul, penulis string, halaman int) Buku {
	// TODO: isi semua field, Tersedia = true
	return Buku{}
}

func deskripsiBuku(b Buku) string {
	// TODO: gunakan fmt.Sprintf dan field-field b
	return ""
}

func main() {
	b := bukuBaru("Hujan di Kota Tua", "Ratna", 240)
	fmt.Printf("%+v\n", b)
	fmt.Println(deskripsiBuku(b))
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)