Hacker Timesnew | past | comments | ask | show | jobs | submitlogin

> constrain those interfaces to be structs or ref-structs

How?

I know of constraints on generic type parameters, but not how to do this. A cursory search is unhelpful.



I think the comment just meant using generic constraints with structs.

e.g.

  interface Foo {
    int Calculate();
  }

  static void CalculateThing<T>(T impl)
  where T: Foo {
    var num = impl.Calculate() * 2;
    Console.WriteLine(num);
  }
Here if you pass a struct that implements 'Foo', 'CalculateThing' will be monomorphized and the dispatch will be zero-cost, same as in Rust.

You can apply additional constraints like `where T: struct` or `allows ref struct`. The last one is a new addition which acts like a lifetime restriction that says that you are not allowed to box T because it may be a ref struct. Ref structs are for all intents and purposes regular structs that can hold so-called "managed references" aka byrefs, which have syntax 'ref T', which is discussed in detail by the article this submission links to (ref structs can also hold other ref structs, you are not limited in nesting, but you are limited in cyclicality).


Yes, this is what I meant




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: