Struct Mapping with #[derive(JuliaStruct)]

RustCall.jl provides automatic struct mapping through the #[derive(JuliaStruct)] attribute, which allows you to seamlessly use Rust structs as first-class Julia objects.

`#[julia]` and `#[derive(JuliaStruct)]`

Inside a rust""" block the two spellings mark a struct the same way, and this page uses both. #[derive(...)] is Rust's syntax for asking the compiler to generate standard behaviour for a type, and listing Clone there (#[derive(JuliaStruct, Clone)]) is how a struct becomes copyable. In a separate crate bound with @rust_crate, write #[julia]; see External Crate Bindings. If Rust's struct / impl syntax is new to you, read Structs and methods first.

Overview

When you add #[derive(JuliaStruct)] to a Rust struct, RustCall.jl automatically:

  • Generates Julia bindings for the struct
  • Creates field accessors (getters and setters)
  • Generates trait implementations (Clone, Debug, etc.) when requested
  • Manages memory lifecycle with automatic finalizers

Basic Usage

Simple Struct

rust"""
#[derive(JuliaStruct)]
pub struct Point2D {
    x: f64,
    y: f64,
}

impl Point2D {
    pub fn new(x: f64, y: f64) -> Self {
        Point2D { x, y }
    }

    pub fn distance(&self) -> f64 {
        (self.x * self.x + self.y * self.y).sqrt()
    }
}
"""

# Create a Point2D instance
p = Point2D(3.0, 4.0)

# Access fields directly
println(p.x)  # => 3.0
println(p.y)  # => 4.0

# Modify fields
p.y = 5.0
println(p.y)  # => 5.0

# Call methods
dist = p.distance()
println(dist)  # => 5.830951894845301
3.0
4.0
5.0
5.830951894845301

With Clone Support

rust"""
#[derive(JuliaStruct, Clone)]
pub struct PersonInfo {
    name: String,
    age: i32,
}

impl PersonInfo {
    pub fn new(name: String, age: i32) -> Self {
        PersonInfo { name, age }
    }

    pub fn get_name(&self) -> String {
        self.name.clone()
    }
}
"""

# Create a person
person = PersonInfo("Alice", 30)
println(person.name)      # => "Alice"
println(get_name(person)) # => "Alice"

# Clone the person
person2 = copy(person)  # Uses Rust's Clone trait

# Both are independent objects
person.age = 31
println(person.age)   # => 31
println(person2.age)  # => 30
Alice
Alice
31
30

Derive Options

The #[derive(JuliaStruct)] attribute supports additional derive options:

Supported Traits

  • Clone: Enables copy() function in Julia
  • Debug: (Reserved for future use)
  • PartialEq: (Reserved for future use)
  • Eq: (Reserved for future use)
  • PartialOrd: (Reserved for future use)
  • Ord: (Reserved for future use)
  • Hash: (Reserved for future use)
  • Default: (Reserved for future use)

Example with Multiple Traits

rust"""
#[derive(JuliaStruct, Clone)]
pub struct Config {
    host: String,
    port: i32,
    timeout: f64,
}

impl Config {
    pub fn new(host: String, port: i32, timeout: f64) -> Self {
        Config { host, port, timeout }
    }
}
"""

config = Config("localhost", 8080, 30.0)
config2 = copy(config)  # Clone support

Field Access

Automatic Getters and Setters

When #[derive(JuliaStruct)] is present, RustCall.jl automatically generates:

  • Getters: Access fields using obj.field_name
  • Setters: Modify fields using obj.field_name = value
rust"""
#[derive(JuliaStruct)]
pub struct Rectangle {
    width: f64,
    height: f64,
}

impl Rectangle {
    pub fn new(width: f64, height: f64) -> Self {
        Rectangle { width, height }
    }

    pub fn area(&self) -> f64 {
        self.width * self.height
    }
}
"""

rect = Rectangle(10.0, 20.0)

# Get field values
w = rect.width   # => 10.0
h = rect.height  # => 20.0

# Set field values
rect.width = 15.0
rect.height = 25.0

# Calculate area
rect_area = rect.area()  # => 375.0

Field Type Mapping

Field types come from the FFI type contract, which is the same table free functions and methods use — a u16 field and a u16 return resolve identically. Every Rust primitive is supported, including i128, u128 and char, plus the std::os::raw aliases and raw pointers:

Rust TypeJulia TypeNotes
i8 … i128, u8 … u128Int8 … Int128, UInt8 … UInt128
f32, f64Float32, Float64
boolBool
usize, isizeCsize_t, Cssize_t
charCharThe C slot is a UInt32 code point; the value is converted, never reinterpreted
*const T, *mut TPtr{T}Resolved recursively; an opaque pointee degrades to Ptr{Cvoid}
StringStringRead as an owned (ptr, len, cap) buffer and released through <Struct>_free_rust_string
&strStringMethod returns are copied to a Julia string

Only a field whose value crosses the boundary on its own gets a getter and a setter: a primitive, a raw pointer or a String, plus, in a generic struct, a field typed by one of the struct's own type parameters. Any other field — a Vec<T>, a HashMap, a Box, another struct held by value — gets none, whether it is pub or not, and the struct binds as an opaque handle that Julia reaches through its methods (#453). Expose such state through a method (pub fn len(&self) -> usize, or one returning a copy in a type the contract covers). See The FFI Type Contract for the full matrix.

Generic Structs

Generic structs are also supported:

rust"""
#[derive(JuliaStruct)]
pub struct Pair<T> {
    first: T,
    second: T,
}

impl<T> Pair<T> {
    pub fn new(first: T, second: T) -> Self {
        Pair { first, second }
    }
}
"""

# Create a Pair with Int32
pair_int = Pair{Int32}(10, 20)
println(pair_int.first)   # => 10
println(pair_int.second)  # => 20

# Create a Pair with Float64
pair_float = Pair{Float64}(3.14, 2.71)
println(pair_float.first)   # => 3.14
println(pair_float.second)  # => 2.71
Note

Generic struct support works for examples like Pair{Int32} and Pair{Float64} shown above. More complex patterns may still need additional testing.

Bounds, Self, and borrowed siblings

A method of a generic struct may take the struct itself by reference — other: &Self or, with the same meaning, other: &Pair<T>. Julia passes the other handle's pointer; the two handles must be the same instantiation and come from the same library image, the borrowed handle must be alive, and a &mut Pair<T> argument may not alias the receiver. Both handles are rooted for the call. A method with a receiver may also return Self: the result is a new handle of that instantiation, bound to the image that allocated it.

In an impl header's bounds, Self is the implementing type, not the type parameter — plain Rust semantics. impl<T: Add<Output = Self>> Pair<T> asks for T: Add<Output = Pair<T>>, which is rarely what a numeric bound wants:

rust"""
#[derive(JuliaStruct)]
pub struct Pair<T> { pub first: T, pub second: T }

// `T: Add<Output = Pair<T>>` — not the elementwise sum this looks like.
// impl<T: Copy + std::ops::Add<Output = Self>> Pair<T> { ... }

// Constrain the parameter itself, and `Self` in the body is `Pair<T>` as usual.
#[julia]
impl<T: Copy + std::ops::Add<Output = T>> Pair<T> {
    pub fn new(first: T, second: T) -> Self { Pair { first, second } }
    pub fn plus(&self, other: &Pair<T>) -> Self {
        Pair { first: self.first + other.first, second: self.second + other.second }
    }
}
"""

Self is rewritten to the block's type only inside the generated wrappers, where a free function has no Self (see Where predicates).

A constructor can be called without naming the parameter — Pair(1.0, 2.0) — when its arguments pin it: each argument whose Rust type is exactly T contributes typeof(arg), and all of them must agree. Otherwise RustCall asks for Pair{T}(...) explicitly, naming the parameter it could not infer.

Memory Management

Structs created with #[derive(JuliaStruct)] are automatically managed by Julia's garbage collector. When a Julia object is reclaimed, its corresponding Rust memory is automatically freed.

Method Binding

All pub fn methods in impl blocks are automatically bound:

rust"""
#[derive(JuliaStruct)]
pub struct Calculator {
    value: f64,
}

impl Calculator {
    pub fn new(value: f64) -> Self {
        Calculator { value }
    }

    pub fn add(&mut self, x: f64) {
        self.value += x;
    }

    pub fn multiply(&mut self, x: f64) {
        self.value *= x;
    }

    pub fn get_value(&self) -> f64 {
        self.value
    }

    pub fn reset(&mut self) {
        self.value = 0.0;
    }
}
"""

calc = Calculator(10.0)
calc.add(5.0)
calc.multiply(2.0)
println(calc.get_value())  # => 30.0
calc.reset()
println(calc.get_value())  # => 0.0

Generic methods of a non-generic struct

Each bound method gets an extern "C" entry point with a fixed symbol, which needs concrete types. A pub fn of a non-generic struct that is generic over a type or a const parameter, or through impl Trait in its signature, therefore cannot be bound, and the block is refused at that method with a compile_error! naming it (#471):

error: `Acc::echo` is generic over `T`: every `pub fn` of a `#[julia]` struct in a
`rust"""` block gets an `extern "C"` entry point, which needs concrete types, ...

RustCall monomorphizes on demand only generic free functions and generic structs. Instead:

  • make the operation a generic free function, instantiated for the argument types of each call;
  • write one non-generic pub fn per type Julia calls, delegating to the generic method; or
  • drop pub from the generic method if Julia does not call it — only pub methods are bound.
impl Acc {
    fn scaled_by<T: Copy + Into<i64>>(&self, k: T) -> i64 { self.total * k.into() }
    pub fn scaled_i32(&self, k: i32) -> i64 { self.scaled_by(k) }
}

#[julia]
pub fn echo<T: Copy>(x: T) -> T { x }

The same holds for a method of a generic struct that has parameters of its own: impl<T> Wrap<T> { pub fn pair<U>(&self, u: U) -> U } is refused at the method (#477), because instantiating Wrap{Int32} binds T and nothing binds U. Methods that use only the struct's parameters are instantiated with it as before.

Lifetime parameters (pub fn pick<'a>(&'a self, s: &'a str) -> usize) are not generics in this sense and are bound as usual. A named lifetime on a struct reference (pub fn sum<'a>(&self, other: &'a Buf) -> i32) is declared on the generated wrapper, bounds included (<'a, 'b: 'a>, where 'b: 'a), so such a method compiles (#477); from Julia the reference is passed as the other object's pointer, sum(a, b.ptr). The #[julia] proc macro in a crate refuses a generic method the same way (#462).

Where predicates

A method's generated wrapper is valid under exactly the assumptions the method is (#482): it declares the lifetime parameters and where clause of the impl block the method is written in (impl<'x> Buf, impl Buf where Buf: Tagged), then the method's own, as written. Self, which the wrapper — a free function — does not have, is spelled as the impl header's type: where Self: Tagged becomes where Buf: Tagged, <Self as Tagged>::Tag becomes <Buf as Tagged>::Tag, and an argument other: &'a Self becomes other: &'a Buf; in expression position too, so where [(); Self::N]: Sized becomes where [(); <Buf>::N]: Sized. No predicate is selected or dropped, so higher-ranked bounds (for<'b> &'b Self: Rel<&'a Buf>), fn-pointer and trait-object types, and a predicate that is the only proof a call is valid all hold on the wrapper as they do on the method. A Self inside a macro invocation (same!(Self): Sized) cannot be spelled that way and is refused at that token; write the type there.

A &str argument is the one place the wrapper's signature differs: it arrives from Julia as a pointer and a length and is rebuilt into a string that lives only for the call. Its lifetime may be related to others as long as it can shrink to the call (s: &'c str with where 'c: 'a and other: &'a Buf is fine). A method that needs it to outlive the call — s: &'static str, a return type that names it (-> &'a i32), an argument that names it other than as its outermost reference (&'a mut &'a Buf), or a type predicate over it (where &'c str: Tr) — is refused at that lifetime with a message naming the method; take String instead.

Receivers

The wrapper receives the object as a pointer and calls the method by its path, <Buf>::m(..) (<Buf as tr::Tr>::m(..) for a method of a trait impl), which passes the receiver exactly as it is declared (#509). A receiver is accepted when it is written as reference layers over Self or over the type as the impl header spells it:

ReceiverWrapper takesJulia object
&self, self: &Self, self: &Buf, self: &&Self*const Bufread
&mut self, self: &mut Self, self: &mut Buf, self: &mut &mut Self*mut Bufchanged in place
self, mut self, self: Self*const Bufread (the method gets a copy; the type must be Copy)

A receiver whose type the syntax can't resolve is refused at the receiver with a compile_error!, and the boundary report lists it as receiver_type. That covers a type alias (self: Ref<'_, Self>), a smart pointer (Box<Self>, Rc<Self>, Arc<Self>, Pin<&mut Self>), and the type spelled differently from the header (self: &crate::Buf in impl Buf). To expose such a method, add a method with an accepted receiver that calls it.

Borrowed struct arguments

An argument that borrows a #[julia] struct of the same crate or block — &Self, &Value, &mut Value, &super::Value, &crate::a::Other, a name a use brings into scope — is passed as the pointer the Julia handle owns (#565):

#[julia]
impl Value {
    #[julia]
    pub fn sum(&self, other: &Value) -> i32 { self.n + other.n }
    #[julia]
    pub fn absorb(&mut self, other: &Value) { self.n += other.n; }
}
#[julia]
pub fn total(a: &Value, b: &Value) -> i32 { a.n + b.n }
a, b = bindings.Value(Int32(2)), bindings.Value(Int32(3))
bindings.sum(a, b)    # 5
bindings.sum(a, a)    # 4: shared borrows may alias
bindings.absorb(a, a) # ArgumentError: a `&mut` borrow may not alias another

The wrapper takes the reference as written, which crosses the C ABI as one thin pointer, so nothing is copied and no register_ffi_struct layout is involved. Before the call the Julia wrapper checks every borrowed argument:

  • It must be the struct's own Julia handle type. Another struct, another module's type of the same name, or the same crate bound twice (an @rust_crate module and a written one) is refused with an ArgumentError.
  • It must not be freed, and its library image must not be closed, exactly as for self.
  • Every handle the call borrows, self included, must come from one library image. After a hot reload, an object of the retired generation and one of the replacement are refused together, because the two may disagree on the struct's layout.
  • A &mut borrow may not alias the receiver or another argument. Rust forbids that, so the call is refused before Rust sees the two references.

Julia roots a borrowed handle for the call only, so only a borrow that ends with the call is converted: its lifetime must be elided, '_, or one the function declares itself without bounds and that neither its where clause nor its return type names. A borrow Rust may keep — &'static Value, a lifetime of the impl block, 'a: 'static — is left as written and is not passed from a handle.

A raw Ptr{Cvoid} (b.ptr) is still accepted and passed through unchecked, as it was before handles were recognised; the caller then vouches for it.

Every borrowed handle is kept rooted for the whole call, so the finalizer of a temporary (total(Value(1), Value(2))) cannot free it mid-call. As for a receiver alone, objects of one retired generation are still passed to the image that runs the call, so a reload that changes a struct's layout needs fresh objects.

Only a path that names the struct with certainty is classified. The pointee is resolved the way an impl header is: by its qualifier, by the module's own items, or by a use that binds the name. A local type of the same name shadows the #[julia] struct, as it does for rustc. A generic pointee (&Holder<i32>), a glob import or a type alias is left as written, and Julia cannot pass it.

Returned references

A method or function may return a reference with an elided lifetime (pub fn get(&self) -> &i32, -> &Self, -> Option<&i32>, -> &'_ i32) (#484). The wrapper takes the receiver as a raw pointer, so it can't copy that return as written. Instead it names the lifetime that Rust's elision rules pick for the method: the receiver's (&self, &'a self), or, with no receiver, the single lifetime of a passed-through argument (fn pick(o: &Buf) -> &i32). Exported symbols don't change.

A reference crosses the C ABI as a pointer, and the FFI contract has no row for &T. So under the default RustCall.FFI_STRICT[] = :error, the block refuses such a method by name, as it always did for a named -> &'a i32. With :warn, the block compiles, and @rust rustcall_Buf_get(obj.ptr)::Ptr{Int32} returns a pointer into the object. That pointer is valid only while the object is. Returning a value (-> i32) is the usual choice.

If the only lifetime is a &str argument's (fn f(s: &str) -> &i32), the returned reference would borrow the string that the wrapper rebuilt for the call, and that string is gone when the wrapper returns. RustCall refuses such a function at that argument, with a message that names it. Return an owned value, or give the return a lifetime that doesn't come from the string. An item whose own output lifetime is ambiguous (fn f(a: &Buf, b: &Buf) -> &i32) gets rustc's E0106 at its own signature, and RustCall generates no wrapper for it.

Static Methods

Static methods (methods without self) are supported on #[derive(JuliaStruct)] types with fields:

rust"""
#[derive(JuliaStruct)]
pub struct MathUtils {
    dummy: i32,
}

impl MathUtils {
    pub fn new() -> Self {
        MathUtils { dummy: 0 }
    }

    pub fn add(a: f64, b: f64) -> f64 {
        a + b
    }

    pub fn multiply(a: f64, b: f64) -> f64 {
        a * b
    }
}
"""

# Call static methods with the type first — the Julia spelling of
# `MathUtils::add(3.0, 4.0)`:
result1 = add(MathUtils, 3.0, 4.0)      # => 7.0
result2 = multiply(MathUtils, 3.0, 4.0) # => 12.0

# The bare form exists too, as long as nothing else in the block is called
# `add` or `multiply`:
result1 = add(3.0, 4.0)                 # => 7.0

A static method dispatches on the type so that it never shares a method table with a free #[julia] fn of the same name: MathUtils::add and a free fn add in one block used to define add(::Any, ::Any) twice and overwrite each other — silently, or as a hard error when the module is precompiled. When such a name exists in the block, only the typed form is generated for the static method and the free function keeps the bare name (#323). The same rule applies to @rust_crate bindings.

Note

Unit struct support is still planned for a future release, so the example above uses a regular struct.

Names Julia reserves

A struct, field or method whose name Julia reserves — end, begin, quote, or any Rust keyword written as a raw identifier (r#for, r#let) — is bound with a trailing underscore, and a raw identifier loses its r# (#514). Free functions follow the same rule, and so do @rust_crate bindings (see External Crate Bindings):

rust"""
#[julia]
pub struct end { pub r#let: i32, pub begin: i32 }

#[julia]
impl end {
    pub fn new(a: i32, b: i32) -> Self { end { r#let: a, begin: b } }
    pub fn quote(&self) -> i32 { self.r#let + self.begin }
}
"""

e = end_(Int32(2), Int32(3))
e.let_, e.begin_   # (2, 3)
quote_(e)          # 5

The exported Rust symbols keep their spelling. A block where the underscore lands on a name it already binds (fn r#for beside fn for_, a field r#let beside let_) is refused with both items named.

Result and Option Returning Methods

A method that returns Result<T, E> or Option<T> is lowered exactly like a free function (#268): the generated extern "C" wrapper returns a #[repr(C)] CResult_<Struct>_<method> / COption_<Struct>_<method> aggregate, and Julia hands you a RustResult{T, E} / RustOption{T}. This is true on all three paths — an inline rust""" block, @rust_crate, and the file write_bindings_to_file writes.

rust"""
#[julia]
pub struct Divider {
    pub scale: i32,
}

impl Divider {
    pub fn new(scale: i32) -> Self { Divider { scale } }

    pub fn checked_div(&self, d: i32) -> Result<i32, String> {
        if d == 0 {
            Err(format!("cannot divide {} by zero", self.scale))
        } else {
            Ok(self.scale / d)
        }
    }

    pub fn ratio(&self, d: i32) -> Option<f64> {
        if d == 0 { None } else { Some(self.scale as f64 / d as f64) }
    }

    pub fn describe(&self, unit: String) -> Result<String, String> {
        if unit.is_empty() {
            Err("empty unit".to_string())
        } else {
            Ok(format!("{} {}", self.scale, unit))
        }
    }
}
"""

d = Divider(Int32(10))

RustCall.unwrap(checked_div(d, Int32(2)))   # => 5
checked_div(d, Int32(0)).value              # => "cannot divide 10 by zero"
RustCall.unwrap(ratio(d, Int32(4)))         # => 2.5
RustCall.is_none(ratio(d, Int32(0)))        # => true
RustCall.unwrap(describe(d, "meters"))      # => "10 meters"

&mut self methods, static methods and the free-function form all behave the same way.

String payloads

A String or &str payload cannot be a field of the C aggregate, so it is lowered to the same owned buffer a String-returning wrapper already uses: <owner>_RustCallOwnedString { ptr, len, cap }, released through <owner>_free_rust_string. The Result lowering and the string lowering therefore compose, and Result<String, String> works. <owner> is the struct for an inline method and <Struct>_<method> for a @rust_crate one, matching the buffer a string-returning method of the same flavour uses.

Julia copies the buffer into a Julia String and releases it immediately, through the release function resolved in the same generation snapshot as the call (see Panics and reloads). Only the active payload is decoded and released; the inactive one is uninitialized on the Rust side.

A &str payload is copied rather than borrowed: unlike a bare &str return, a payload sits inside an aggregate that outlives the call's temporaries, so one owned shape keeps the release rule true in every case.

Panics

A panic inside a Result/Option-returning method is caught at the boundary exactly as anywhere else: the wrapper returns the panicked() sentinel (the Err / None discriminant with no payload initialized), Julia reads the panic channel before it decodes anything, and raises RustCall.RustPanicError.

A method of a non-generic struct returning Result<Self, E> (or the struct as the impl header spells it) with a supported error payload is exposed as RustResult{Wrapper,E}. The wrapper boxes the Ok value, so Ok owns a new Julia wrapper with the destructor and liveness flag of the library generation that ran the call; Err carries the error and allocates no wrapper. The panic channel is checked before anything is decoded. An inherent static method is bound as the struct's constructor (Value(n), #559); a method with a receiver (fn duplicate(&self) -> Result<Self, String>, fn split(&mut self) -> Result<Value, i32>) or a trait method keeps its own name and returns an independent object, leaving the receiver valid (#564).

The producing crate must use rustcall_julia_macros 0.5.0 or later for a constructor, and 0.6.0 or later for any other method. Before the call, the binding checks the producer's boxed-result ABI marker (<symbol>_boxed_result_v1) and refuses an older producer library instead of interpreting its by-value Self as an owning pointer. After upgrading RustCall, rebuild its extractor with Pkg.build("RustCall") and regenerate any written crate bindings. RustCall 0.9.0 with its default strict FFI policy rejects the unsupported Self payload before the call; do not disable strict FFI checking to bypass this incompatibility.

What is not lowered

  • A payload the aggregate cannot carry (Vec<T>, Box<T>, a HashMap, …) keeps the previous behaviour: the method returns the type as written and the manifest reports return_kind = plain. On a free function the same payload is a compile error, which is the older and stricter rule.
  • The methods of a generic struct are monomorphized on demand and return the type as written; Result/Option lowering does not apply to them.

Generic objects and registration updates

One generic struct instantiation builds its applicable constructor, destructor, methods and accessors into one library. Each object keeps that library's method snapshots as well as its destructor: replacing the source registration affects new objects, not the layout or method implementation used by an existing object. An existing object's string release and panic channel stay in its original image. Registration prepares all members outside the state lock, then publishes the complete group in one transaction, removing methods absent from the replacement. This does not erase the compiled member snapshots that existing objects own.

A method with stricter trait bounds, or additional method-local type parameters not bound by the struct instantiation, does not prevent construction. Such a method is not part of that object's compiled member set. Calling an unavailable member reports an error rather than silently entering another generation. Calling a method after explicitly finalizing its receiver also reports an error. Methods and field wrappers also reject an object whose captured image has been explicitly closed, even when its Rust allocation pointer is still non-null. Retirement leaves the image mapped and does not disable existing objects.

Best Practices

1. Always Use #[derive(JuliaStruct)]

For structs that you want to use in Julia, always add the attribute:

#[derive(JuliaStruct)]  // ✅ Good
pub struct MyStruct {
    // ...
}

2. Use Clone for Expensive Operations

If you need to copy structs frequently, derive Clone:

#[derive(JuliaStruct, Clone)]  // ✅ Good for copyable structs
pub struct Config {
    // ...
}

3. Keep Structs Simple

Prefer simple field types that map well to Julia:

#[derive(JuliaStruct)]
pub struct Point {
    x: f64,  // ✅ Good: simple type
    y: f64,
}

4. Use Methods for Complex Operations

For complex operations, use methods instead of exposing internal state:

#[derive(JuliaStruct)]
pub struct BankAccount {
    balance: f64,
}

impl BankAccount {
    pub fn new(balance: f64) -> Self {
        BankAccount { balance }
    }

    pub fn withdraw(&mut self, amount: f64) -> Result<f64, String> {
        if amount > self.balance {
            Err("Insufficient funds".to_string())
        } else {
            self.balance -= amount;
            Ok(self.balance)
        }
    }

    pub fn get_balance(&self) -> f64 {
        self.balance
    }
}

Limitations

Current Limitations

  1. Nested structs: Nested structs are not yet fully supported
  2. Complex generics: Very complex generic constraints may not work
  3. Lifetime parameters: Lifetime parameters are not supported
  4. Associated types: Associated types in traits are not supported

Workarounds

For nested structs, use pointers or references:

#[derive(JuliaStruct)]
pub struct Outer {
    inner: *mut Inner,  // Use pointer instead of direct nesting
}

#[derive(JuliaStruct)]
pub struct Inner {
    value: i32,
}

Examples

Complete Example: 2D Vector

rust"""
#[derive(JuliaStruct, Clone)]
pub struct Vec2DD {
    x: f64,
    y: f64,
}

impl Vec2DD {
    pub fn new(x: f64, y: f64) -> Self {
        Vec2DD { x, y }
    }

    pub fn zero() -> Self {
        Vec2DD { x: 0.0, y: 0.0 }
    }

    pub fn add(&self, other: &Vec2DD) -> Vec2DD {
        Vec2DD {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }

    pub fn scale(&mut self, factor: f64) {
        self.x *= factor;
        self.y *= factor;
    }

    pub fn magnitude(&self) -> f64 {
        (self.x * self.x + self.y * self.y).sqrt()
    }

    pub fn normalize(&mut self) {
        let mag = self.magnitude();
        if mag > 0.0 {
            self.scale(1.0 / mag);
        }
    }
}
"""

# Create vectors
v1 = Vec2DD(3.0, 4.0)
v2 = Vec2DD(1.0, 2.0)

# Access fields
println("v1: ($(v1.x), $(v1.y))")  # => v1: (3.0, 4.0)

# Modify fields
v1.x = 5.0
println("v1: ($(v1.x), $(v1.y))")  # => v1: (5.0, 4.0)

# Call methods
v3 = v1.add(v2)
println("v3: ($(v3.x), $(v3.y))")  # => v3: (6.0, 6.0)

# Static method
v_zero = Vec2DD.zero()
println("zero: ($(v_zero.x), $(v_zero.y))")  # => zero: (0.0, 0.0)

# Clone
v4 = copy(v1)
v4.scale(2.0)
println("v1 magnitude: $(v1.magnitude())")  # => v1 magnitude: 6.4031242374328485
println("v4 magnitude: $(v4.magnitude())")  # => v4 magnitude: 12.806248474865697
Owned results

Explicit concrete facade mappings support direct owned results and Result<Owner, E>, including a result owned by another declared wrapper. Select the owner with return_wrapper; the actual returned value must satisfy the annotated-owner, Sized and 'static proofs. Receiver and input borrows remain scoped to the synchronous call. See composed facade mappings.

Troubleshooting

Struct Not Found

If you get an error that the struct is not found, make sure:

  1. The struct is marked with pub
  2. The struct has #[derive(JuliaStruct)]
  3. The struct is defined in the rust"" block
// ❌ Bad: missing pub
struct MyStruct { ... }

// ✅ Good
#[derive(JuliaStruct)]
pub struct MyStruct { ... }

Field Access Errors

If field access doesn't work:

  1. Make sure the struct has #[derive(JuliaStruct)]
  2. Check that field names match exactly
  3. Verify field types are supported

Clone Not Working

If copy() doesn't work:

  1. Add Clone to the derive list: #[derive(JuliaStruct, Clone)]
  2. Make sure all fields implement Clone in Rust

See Also