mdempsky / unconvert

Remove unnecessary type conversions from Go source
BSD 3-Clause "New" or "Revised" License
377 stars 26 forks source link

Can and should unconvert simplify this case? #7

Closed dmitshur closed 5 years ago

dmitshur commented 8 years ago

Suppose there's a declaration of a []int32 slice done in the following way:

x := []int32{
    (int32)(1),
    (int32)(5),
    (int32)(8),
}

Is there a reason unconvert can't or shouldn't simplify it to:

x := []int32{
    1,
    5,
    8,
}

Since constants are used, the type conversion is not needed, as the constants will have their types inferred correctly from the context. Any thoughts?

mdempsky commented 8 years ago

Nice, I agree the type conversions there are unnecessary because of context, just like in

var x int32 = int32(1)

It should also work the same for struct and map literals.

dmitshur commented 8 years ago

Great!

As I understand, this will only be possible in some cases. For example, if it looks like this:

var x, y, z = 1, 2, 3

s := []int32{
    int32(x),
    int32(y),
    int32(z),
    4,
    5,
}

Then it won't be possible, since variables x, y and z will need to be converted. But if they were declared as int32, then it could be dropped.

It should also work the same for struct and map literals.

Yep. Also arrays. I didn't mention others because I wanted to start the conversation simpler.

mdempsky commented 8 years ago

Correct, in the int32(x) case, x's type is int, so it's a necessary conversion. It's only unnecessary if x is untyped or int32 already.

dmitshur commented 7 years ago

I suspect this issue is also related to https://github.com/mdempsky/unconvert/issues/20#issuecomment-326457163. Specifically, it could be that the reason this case isn't detected and reported because the constants would become untyped as a result.

mdempsky commented 5 years ago

Going to close as a duplicate of #20 since the latter has more details.