Structs in Racket

Structs in Go are typed collections of fields. They’re useful for grouping data together to form records.

#lang racket

; This `person` struct type has `name` and `age` fields.
(struct person (name age))

; `new-person` constructs a new person struct with the given name.
(define (new-person name)
  (define p (person name 42))
  p)

(define (main)
  ; This syntax creates a new struct.
  (displayln (person "Bob" 20))

  ; You can name the fields when initializing a struct.
  (displayln (person "Alice" 30))

  ; Omitted fields will be zero-valued.
  (displayln (person "Fred" 0))

  ; An `&` prefix yields a pointer to the struct in Go, but in Racket, a struct is already a reference.
  (displayln (new-person "Ann"))

  ; It’s idiomatic to encapsulate new struct creation in constructor functions
  (displayln (new-person "Jon"))

  ; Access struct fields with a dot.
  (define s (person "Sean" 50))
  (displayln (person-name s))

  ; Structs are mutable in Go. In Racket, you need to use set-struct-field! with mutable structs.
  (define sp (set-person-age! s 51))
  (displayln (person-age s))

  ; If a struct type is only used for a single value, we don’t have to give it a name.
  ; The value can have an anonymous struct type.
  (define dog (struct "dog"
                      (name isGood)
                      #:mutable))
  (define my-dog (dog "Rex" #true))
  (displayln my-dog)
)

(main)

To run the program, save it to a file such as struct-example.rkt and use Racket to run it.

$ racket struct-example.rkt
(person "Bob" 20)
(person "Alice" 30)
(person "Fred" 0)
(person "Ann" 42)
(person "Jon" 42)
"Sean"
50
51
(dog "Rex" #true)

Next example: Methods.

In this example, we’ve translated several fundamental operations involving structs from Go to Racket, adapting the syntax and idioms accordingly.