News for hackers. Stuff that matters.
Re:The Next Step for Generics by neilparikh on Wednesday June 17, 2020 @03:12AM (#23548675)
What about genetics for phantom types?

Ex.

    class ID<T> {
      int id;
    }
The idea is that an ID is just an int under the hood, but ID<User> and ID<Post> are different types so you can’t accidentally pass in a user id where a post is is expected.

Now, this is just a simple example that probably won’t catch too many bugs, but you can do more useful things like have a phantom parameter to represent if the data is sanitized, and then make sure that only sanitized strings are displayed.

Re:The Next Step for Generics by metrognome on Wednesday June 17, 2020 @03:41AM (#23548867)
Just to note, for this specific example, Go supports this with type definitions:

  // UserID and PostID are distinct types
  type UserID int
  
  type PostID int
Re:The Next Step for Generics by njs12345 on Wednesday June 17, 2020 @06:07AM (#23549706)
This isn't quite the same, because it's just an alias - you can pass a UserID to a function accepting a PostID: https://play.golang.org/p/nSOgcJs_66y

It still provides a documentation benefit of course.

EDIT: Whoops, yes, as lentil points out, they are indeed distinct types not aliases. So it does provide the benefit of the Rust solution.

Re:The Next Step for Generics by lentil on Wednesday June 17, 2020 @06:19AM (#23549780)
No, it's not an alias, they are distinct types. You can't use the types interchangeably (unless you cast them).

Your playground example didn't try to pass a UserID to a function accepting a PostID, but if you do that, you'll see the error:

https://play.golang.org/p/vyiJ_sLzy4O

Re:The Next Step for Generics by neilparikh on Wednesday June 17, 2020 @04:17AM (#23549069)
Oh neat! Most languages make it a little bit verbose to create these kinds of wrapper types for type safety (with zero overhead), so it's nice that Go has that.

I think the generic approach is a little bit better because of the flexibility, but this approach is still better than not having it at all.