Template types with unknown fields

⚓ Rust    📅 2025-06-27    👤 surdeus    👁️ 7      

surdeus

Warning

This post was published 43 days ago. The information described in this article may have changed.

Consider the following sample code;

fn a_plus_b<T>(t: T) -> i32 {
    t.a + t.b     // <== error[E0609]: no field `a` and `b` on type `T`
}

struct AB {a: i32, b: i32}

fn main() {
    println!("{}", a_plus_b(AB{a:10, b:20})); // <=== won't work
}

The compiler fails when it tries to compile fn a_plus_b because it can't "see" a and b fields on T. A similar construct (where T's fields are not yet know) would work in C++, because templates are 'lazy evaluated/compiled' on concrete 'invocation/use'.

Question 1: I'm guessing the Rust compiler some good reasons to know T when it compiles a_plus_b, though I'm curious what these reasons are and why not lazily evaluate templates?

Question 2: I am also guessing that the only way to make it work is with traits (e.g. trait MyT with methods such as get_a/get_b/get_mut_a/get_mut_b). Doable and but a lot of boiler plate. Is there any other way apart from traits?

Wish: Could be a nice feature if somehow we are able to satisfy the compiler with where clause like (probably in 2030 :slight_smile):

fn a_plus_b<T>(t: T) -> i32 
where 
    T.a: i32,
    T.b: i32,
{
    t.a + t.b  
}

4 posts - 4 participants

Read full topic

🏷️ rust_feed