Structs in Miranda

The miranda variable specifies the target language as Python. Below is the translated code from the provided example.

Go’s *structs* are typed collections of fields. They’re useful for grouping data together to form records.

This `person` struct type has `name` and `age` fields.

```python
class Person:
    def __init__(self, name: str, age: int = 42):
        self.name = name
        self.age = age

The new_person function constructs a new person struct with the given name.

def new_person(name: str) -> Person:
    return Person(name)

This syntax creates a new struct.

print(Person("Bob", 20))

You can name the fields when initializing a struct.

print(Person("Alice", 30))

Omitted fields will be zero-valued.

print(Person("Fred"))

To yield a pointer to the struct, in Python, you can directly return the object instance.

print(new_person("Ann"))

It’s idiomatic to encapsulate new struct creation in constructor functions.

print(new_person("Jon"))

Access struct fields with a dot.

p = Person("Sean", 50)
print(p.name)

You can also use dots with struct pointers - the pointers are automatically dereferenced.

p.age = 51
print(p.age)

Structs are mutable.

sp = p
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. The value can have an anonymous struct type. This technique is commonly used for table-driven tests.

dog = lambda: None
dog.name = "Rex"
dog.is_good = True
print(dog.name, dog.is_good)

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

$ python structs.py
<__main__.Person object at 0x...>
<__main__.Person object at 0x...>
<__main__.Person object at 0x...>
<__main__.Person object at 0x...>
<__main__.Person object at 0x...>
Sean
51
Rex True

Next example: Methods.