Can rust declare one-time struct when used in generic type

like typescript, we can declare an interface "on-demand" in generic type

const arr : Array<{
foo:string
}>

// no need to declare interface explictly like ...
interface Foo{
foo:string
}

const arr1: Array<Foo>

can I do this in rust? or is there any convinient syntax to do so

No, Rust doesn't have structural UDTs. You can use a tuple instead for simpler types.

2 Likes

The crate structx provides simulation of anonymous struct. You can use Structx!{ foo: String } to both define the type and refer to it; or use structx!{ foo: String::from(“lorum ipsum”) } to both define the type and refer to the value. It’s not perfect but can work under many circumstances.

Note, however, that you can declare a struct also within a function (possibly dependent on type parameters of the function):

fn foo<T: std::fmt::Display>(name: T) {
    struct Adhoc<T> {
        name: T,
    }
    let doit = |adhoc: &Adhoc<T>| {
        println!("{}", adhoc.name);
    };
    let adhoc = Adhoc::<T> { name };
    doit(&adhoc);
    doit(&adhoc);
}

fn main() {
    foo("Günther Lause".to_string());
}

(Playground)

Output:

Günther Lause
Günther Lause

It still requires you to declare them though. But they don't need to be declared outside the function or block.

Those T aren't connected. [1]

Also compare and contrast this and this.

 fn foo<T: std::fmt::Display>(name: T) {
-    fn f<T>(t: T) {}
+    fn f(t: T) {}
 }
error[E0401]: can't use generic parameters from outer function
 --> src/main.rs:2:13
  |
1 | fn foo<T: std::fmt::Display>(name: T) {
  |        - type parameter from outer function
2 |     fn f(t: T) {}
  |         -   ^ use of generic parameter from outer function
  |         |
  |         help: try using a local generic parameter instead: `<T>`

  1. Honestly not 100% sure if that was the idea, but... ↩︎

1 Like

Oops, you're right. I wasn't aware of this.

I mean… you still can declare the struct inside the function for keeping your namespace a bit more clean, but yeah, the struct isn't really dependent on the type parameter(s) of the function.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.