Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

No type mapping between inside and outside function for generics #10

Open
jmatss opened this issue Aug 23, 2021 · 0 comments
Open

No type mapping between inside and outside function for generics #10

jmatss opened this issue Aug 23, 2021 · 0 comments

Comments

@jmatss
Copy link
Owner

jmatss commented Aug 23, 2021

Currently there are no mapping between generic types coming from outside a function to inside. I.e. the generics are mapped to the declaration/prototype of the function, but the inferred type is never mapped/checked against the generic type inside the function body.

fn test_fn<T>(x: T) {
    x + (3.0 as f32)
}

fn main() -> i32 {
    var input: f64 = 5.0
    test_fn(input)
    return 0
}

Given the example above: The generic type of the function call at line 7 will be inferred to f64 (the type of input). Looking only at the function declaration of test_fn (ignoring the body), it looks like f64 is a valid replacement for T (since it has no restrictions). But if we look in the body of test_fn we can see that T must be of type f32 to be valid.

The two possible options to fix this would be to:

  1. Reject the body of test_fn. Since there are no restrictions/enforcements of what type T can be in a where-clause, it should not be allowed to do addition on a value with the type.
  2. Map the generics from declaration to inside the function body. Using the example above, we would be able to see that a value of type T is added with a f32 which means that T must be of type f32. This is a possible options since there are currently no dynamic dispatch, the generics must be known at compile time anyways.

My preferred option is the first one since it keeps all restrictions enforced on the generics in the function declaration, there are no hidden restrictions inside the function body. It is already possible to enforce traits on the generics in the function declaration, so I feel like that is good enough (could ex. enforce a Addition trait on the generic type to allow addition in the function body).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant