Structs in Logo

Our first program will demonstrate how to use structs. Here’s the full source code translated into Python:

class Person:
    def __init__(self, name, age=0):
        self.name = name
        self.age = age

def new_person(name):
    p = Person(name)
    p.age = 42
    return p

def main():
    # This syntax creates a new struct
    print(Person("Bob", 20))
    
    # You can name the fields when initializing a struct
    print(Person(name="Alice", age=30))
    
    # Omitted fields will be zero-valued
    print(Person(name="Fred"))
    
    # An ampersand prefix yields a reference to the struct (Python uses references by default)
    print(Person(name="Ann", age=40))
    
    # It’s idiomatic to encapsulate new struct creation in constructor functions
    print(new_person("Jon"))
    
    # Access struct fields with a dot
    s = Person(name="Sean", age=50)
    print(s.name)
    
    # Structs are mutable
    sp = s
    print(sp.age)
    sp.age = 51
    print(sp.age)
    
    # If a struct type is only used for a single value, we don’t have to give it a name
    dog = type("Dog", (object,), {"name": "Rex", "is_good": True})()
    print(dog)

if __name__ == "__main__":
    main()

To run the program, put the code in a file named structs.py and use python to execute it.

$ python structs.py

The expected output would be:

<__main__.Person object at 0x7f8e5c321940>
<__main__.Person object at 0x7f8e5c3219d0>
<__main__.Person object at 0x7f8e5c321a30>
<__main__.Person object at 0x7f8e5c321a90>
<__main__.Person object at 0x7f8e5c321af0>
Sean
50
51
<__main__.Dog object at 0x7f8e5c321b50>