3 ms·
This is exactly what C does. #include <stdio.h> typedef struct { double v; } Celsius; typedef struct { double v; } Fahrenheit; void print_celsius(C
by wBI8j2bsb 9y ago
This is exactly what C does.
#include <stdio.h>
typedef struct { double v; } Celsius;
typedef struct { double v; } Fahrenheit;
void
print_celsius(Celsius temperature) {
printf("Temperature is %f", temperature.v);
}
void
compile_error(Fahrenheit temperature)
{
print_celsius(temperature);
}
I suspect LLVM will clean this up to plain floats as well.
- simias 9y agoYeah, C and Rust work the same way here (as far as I can tell). Rust can also define type aliases (with the 'type' keyword) but they're not new types much like C typedefs. The only advantage of Rust in this case is that its tuple syntax can be a bit nicer than C structs and the language supports overloading so that you can reimplement the comparison operators for instance (or do more complicated things, for instance if you have a "decibel" type that must have a special addition implementation)
- tom_mellior 9y agoWhether any compiler "cleans this up" depends in the system's ABI; parameter calling conventions are not up to the compiler to decide (unless it can prove that a given function cannot be called from code it does not control). That said, yes, modern ABIs for modern machines usually pass single-element structures of primitive types in registers of the appropriate type. x86 (32-bit) is not modern in this sense: depending on the exact ABI used, these structures might well be passed on the stack or in an integer register.
- jononor 9y agoOr if the calls are inlined. Not sure if say Rust can/does this more aggresively than C or C++ (or vica versa).
- deleted 9y ago[deleted]