-
Notifications
You must be signed in to change notification settings - Fork 12.9k
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
Compiler unable to infer obvious types #120256
Comments
Reproducer minimized from the issue description to better describe what's going on: struct Vector2<N = f32>
{
x: N,
y: N,
}
impl<N> Vector2<N>
{
pub fn new(x: f32, y: f32) -> Vector2<f32>
{
Vector2 { x, y }
}
}
fn main()
{
let _: Vector2<f32> = Vector2::new(1.0, 2.0); //~ ERROR type annotations needed
//~^ cannot infer type of the type parameter `N` declared on the struct `Vector2`
//~| HELP consider specifying the generic argument
} |
In this case, you can easily fix this by changing the impl header from impl Vector2
{
pub fn new(x: f32, y: f32) -> Vector2<f32>
{
Vector2 { x, y }
}
} Which can be further simplified to: impl Vector2
{
pub fn new(x: f32, y: f32) -> Self
{
Self { x, y }
}
} |
Closing as a duplicate of #98931. |
Thank you, this is exactly what I wanted! I feel like this could be a compiler suggestion though! /pos For anyone in the future I ended up with this to have both generic capacity and f32 defaults: // --snip--
impl Vector2
{
pub fn new(x: f32, y: f32) -> Vector2::<f32>
{
return Vector2 { x: x, y: y };
}
}
impl<N> Vector2<N>
{
// note for this you will need to specify the exact type, such as
// 1.0 as i16 since rust will use i32 -> f64 in that order, when possible.
pub fn new_as<T>(x: T, y: T) -> Vector2::<T>
{
return Vector2::<T> { x: x as T, y: y as T }
}
}
// --snip-- |
I tried this code:
I tried much less type annotated versions getting increasingly annoyed, until I tried that, which of course still didn't work. I know the simple fix is to add
::<f32>
-- the compiler can tell be that. But with all the type annotations I feel like it should be able to figure out that thats just what I want. I mean, if I specifylet x = 1.0
I don't need to tell it its an f64!Normally I love type hinting, but with the amount vectors are used in gamedev--with almost all of them being f32--it feels awkward and bad UX to need to specify every time. I don't quite know if this is a bug, but I feel like it falls into that category. Especially since its returning a Vector2 with two paramaters which are explictly f32
Instead, this happened: Compiler error:
Meta
rustc --version --verbose
:(also tried on stable, identical issue)
And yes this was with rust backtrace, I don't know why its the same. ![image](https://github.com/rust-lang/rust/assets/94419893/4b7cb6d0-fc27-4020-9e3f-c349b8243cf6)
The text was updated successfully, but these errors were encountered: